我们可以在PHP中的一行上做多个爆炸声明吗?

时间:2012-05-14 04:42:45

标签: php explode

我们可以在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)

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

5 个答案:

答案 0 :(得分:15)

如果您希望将字符串拆分为多个分隔符,则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 
)

答案 1 :(得分: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] => )
// )

?>

答案 2 :(得分: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;

} 

答案 3 :(得分:0)

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

$text = preg_split('/( |,|&)/', $text);

答案 4 :(得分:0)

我会选择strtok(),例如

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

while ($token !== false) {
    echo $token . "\n";
    $token = strtok($delimiter);
}