我正在寻找一种类似爆炸但使用多个字符串分隔符的东西,即
+ - (
都可以是分离器。
例如,在"分解"以下字符串之后:
$string = 'We are 3+4-8 - (the + champions'
我应该将其作为$string[0]:
['We are 3+4-8']
有没有这样的功能?
$string = 'We are - (the + champions';
$words = preg_split('@['W]+@', $string)
有了这个,你就可以获得[我们,是,冠军]
$string = 'We are - (the + champions';
$words = preg_split('/['+'-'(]/', $string)
通过此操作,您可以保留获得["我们是"、"、"the"、"champions"]的空白区域;这将是必要的修剪。
$string = 'We are 3+4-8 - (the + champions';
$words = preg_split('/['+'-] |['(]/', $string)
有了这个,你最终获得了["我们是3+4+8","冠军","champions"]。在这种情况下,不需要修剪。
将preg_split()
与字符类一起使用。
$chars = '+-(';
$regexp = '/[' . preg_quote($chars, '/') . ']/';
$parts = preg_split($regexp, $string);
忘了补充一点,如果您试图解析表达式(如搜索查询(,preg_split()
不会剪切它,您将需要一个成熟的解析器。我认为Zend框架中一定有一个。
这将通过-
、+
或(
分割字符串
$result = preg_split(/[ '- ]|[ '+ ]|[(]/im, $string);
$i = 0;
foreach ($result as $match){
$result[$i] = trim($match);
}
$string = 'We are - (the + champions';
$split = preg_split('/['-,'(,'+]/', $string);
怎么样:
$str = 'We are 3+4-8 - (the + champions';
$res = preg_split('/'s+[+(-]'s+/', $str);
print_r($res);
输出:
[0] => We are 3+4-8
[1] => (the
[2] => champions