2

我想内爆一个带有多个分隔符的字符串。我已经用这个 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()?),以便它匹配这些值, . | :并按照它在字符串中出现的顺序将变量设置为数组。这可能吗?

4

1 回答 1

2
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;

The output of this is:

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 :)

You can see it working here.

For more information what's the function of strpbrk in this script, see here.

It's my first contribution to Stack Overflow, hope it helps.

于 2013-11-11T09:08:36.013 回答