7

我们可以在 PHP 中做多个explode() 吗?

例如,要做到这一点:

foreach(explode(" ",$sms['sms_text']) as $no)
foreach(explode("&",$sms['sms_text']) as $no)
foreach(explode(",",$sms['sms_text']) as $no)

一体式爆炸是这样的:

foreach(explode('','&',',',$sms['sms_text']) as $no)

最好的方法是什么?我想要的是在一行中拆分多个分隔符上的字符串。

4

5 回答 5

17

如果您想用多个分隔符分割字符串,也许preg_split是合适的。

$parts = preg_split( '/(\s|&|,)/', 'This and&this and,this' );
print_r( $parts );

结果是:

Array ( 
  [0] => This 
  [1] => and 
  [2] => this 
  [3] => and 
  [4] => this 
)
于 2012-05-14T04:47:31.020 回答
4

这是我在 PHP.net 找到的一个很好的解决方案:

<?php

//$delimiters must be an array.

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

print_r($exploded);

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

?>
于 2014-12-04T18:02:28.920 回答
2

你可以用这个

function multipleExplode($delimiters = array(), $string = ''){

    $mainDelim=$delimiters[count($delimiters)-1]; // dernier

    array_pop($delimiters);

    foreach($delimiters as $delimiter){

        $string= str_replace($delimiter, $mainDelim, $string);

    }

    $result= explode($mainDelim, $string);
    return $result;

} 
于 2012-05-14T04:46:10.740 回答
0

您可以使用preg_split()函数使用正则表达式分割字符串,如下所示:

$text = preg_split('/( |,|&)/', $text);
于 2012-05-14T04:48:03.983 回答
0

我会去strtok(),例如

$delimiter = ' &,';
$token = strtok($sms['sms_text'], $delimiter);

while ($token !== false) {
    echo $token . "\n";
    $token = strtok($delimiter);
}
于 2012-05-14T04:52:01.137 回答