【问题标题】:PHP - Multiple delimiter implodePHP - 多个分隔符内爆
【发布时间】:2013-09-12 06:10:11
【问题描述】:

我想用多个分隔符分解一个字符串。我已经用这个 PHP 函数 eplode 了:

function multiexplode ($delimiters,$string) {
    $ready = str_replace($delimiters, $delimiters[0], $string);
    $launch = explode($delimiters[0], $ready);
    return  $launch;
}

$text = "here is a sample: this text, and this will be exploded. this also | this one too :)";
$exploded = multiexplode(array(",",".","|",":"),$text);

这个输出是:

Array (
   [0] => here is a sample
   [1] =>  this text
   [2] =>  and this will be exploded
   [3] =>  this also 
   [4] =>  this one too 
   [5] => )
)

我可以使用以下多个分隔符来内爆这个数组吗:,.|:

编辑:

为了定义规则,我认为这是最好的选择:

$test = array(':', ',', '.', '|', ':');
$i = 0;
foreach ($exploded as $value) {
    $exploded[$i] .= $test[$i];
    $i++;
}
$test2 = implode($exploded);

$test2 的输出为:

here is a sample: this text, and this will be exploded. this also | this one too :)

我现在只需要知道如何定义 $test 数组(可能与 preg_match()?),以便它匹配这些值 , . | : 并按顺序设置变量它在字符串中出现的地方变成了一个数组。这可能吗?

【问题讨论】:

  • 您需要定义如何应用分隔符的规则。
  • 对于从explode 得到的数组,如果您想使用4 个字符(,.|:)进行内爆,您希望结果如何?
  • @mario 您建议的解决方案应该是什么样的?恕我直言,删除多个分隔符很容易 - 如图所示 - 但不可能制作方法 multiimplode()
  • @hek2mgl 没错,我完全忽略了 OP 的含义。这显然不是一个可逆的过程。
  • @mario OK.. 如果你能给我一个我会吃熊的方法。 (或类似的东西;)

标签: php arrays explode delimiter implode


【解决方案1】:
function multiexplode ($delimiters,$string) {
    $ready = str_replace($delimiters, $delimiters[0], $string);
    $launch = explode($delimiters[0], $ready);
    return  $launch;
}

$string = "here is a sample: this text, and this will be exploded. this also | this one too :)";
echo "Input:".PHP_EOL.$string;

$needle = array(",",".","|",":");
$split = multiexplode($needle, $string);

$chars = implode($needle);
$found = array();

while (false !== $search = strpbrk($string, $chars)) {
    $found[] = $search[0];
    $string = substr($search, 1);
}

echo PHP_EOL.PHP_EOL."Found needle:".PHP_EOL.PHP_EOL;
print_r($found);

$i = 0;
foreach ($split as $value) {
    $split[$i] .= $found[$i];
    $i++;
}

$output = implode($split);
echo PHP_EOL."Output:".PHP_EOL.$output;

这个的输出是:

Input:
here is a sample: this text, and this will be exploded. this also | this one too :)

Found needle:

Array
(
    [0] => :
    [1] => ,
    [2] => .
    [3] => |
    [4] => :
)

Output:
here is a sample: this text, and this will be exploded. this also | this one too :)

你可以看到它在工作here

更多信息strpbrk在这个脚本中的作用是什么,见here

这是我对 Stack Overflow 的第一个贡献,希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 2011-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多