如何在有角色时内爆一个字符串?

时间:2012-07-20 09:18:43

标签: php regex implode

例如,这是我的字符串:

$text = "Iphone 4, Iphone 4S; Iphone 5, Iphone 3. Iphone 3S";

分裂字符串:

$splitting_strings = array(".", ";", ".");
$result = array (
   0 => "Iphone 4",
   1 => "Iphone 4S",
   2 => "Iphone 5",
   3 => "Iphone 3",
   4 => "Iphone 3S"
);

我正在使用此代码:

$regex = '/(' . implode('|', $splitting_strings) . ')/';
print_r(implode($regex, $text));

3 个答案:

答案 0 :(得分:2)

您可以使用preg_split

$text = "Iphone 4, Iphone 4S; Iphone 5, Iphone 3. Iphone 3S"; 
$array = preg_split("/[\s]*[,][\s]*/", $text);
print_r($array);
// Array ( [0] => Iphone 4 [1] => Iphone 4S [2] => Iphone 5 [3] => Iphone 3 [4] => Iphone 3S )

编辑:

$array = preg_split("/[\s]*[,]|[;]|[.][\s]*/", $text);

答案 1 :(得分:1)

<?php
$text = "Iphone 4, Iphone 4S; Iphone 5, Iphone 3. Iphone 3S";

$splitting_strings = array_map( 'preg_quote', array('.', ';', '.', ',' ) );

$result = array_map( 'trim', preg_split( '~' . implode( '|', $splitting_strings ) . '~', $text ) ); 

$result的值现在与您的相同。请注意,我已经使用preg_quote(以逃避字符)作为修剪。

答案 2 :(得分:0)

只是为了显示使用正则表达式的替代方法(通过正则表达式解决方案更有效)。

$text = "Iphone 4, Iphone 4S; Iphone 5, Iphone 3. Iphone 3S";
$separators = ',;.';

$word = strtok($text, $separators);
$arr = array();
do {
    $arr[] = $word;
    $word = strtok($separators);
} while (FALSE !== $word);

var_dump($arr);