我正在寻找像爆炸一样但使用多个字符串分隔符的东西,即
+ - (
可能都是分隔符。
例如,在“爆炸”后面的字符串:
$string = 'We are 3+4-8 - (the + champions'
我应该把它作为$ string [0]:
['We are 3+4-8']
有没有这样的功能?
答案 0 :(得分:2)
将preg_split()
与字符类一起使用。
$chars = '+-(';
$regexp = '/[' . preg_quote($chars, '/') . ']/';
$parts = preg_split($regexp, $string);
忘记添加,如果您尝试解析表达式(例如搜索查询),preg_split()
将不会删除它,您将需要一个完整的解析器。我认为Zend Framework必须有一个。
答案 1 :(得分:2)
$string = 'We are - (the + champions';
$words = preg_split('@[\W]+@', $string)
通过这个你获得[我们,是,冠军]
$string = 'We are - (the + champions';
$words = preg_split('/[\+\-\(]/', $string)
通过这种方式,您可以保留获得['我们','',''','冠军']的空格;这将是必要的修剪。
$string = 'We are 3+4-8 - (the + champions';
$words = preg_split('/[\+\-] |[\(]/', $string)
有了这个,最后,你获得['我们是3 + 4 + 8',''','冠军']。在这种情况下不需要修剪。
答案 2 :(得分:1)
这会将您的字符串拆分为-
,+
或(
$result = preg_split(/[ \- ]|[ \+ ]|[(]/im, $string);
$i = 0;
foreach ($result as $match){
$result[$i] = trim($match);
}
答案 3 :(得分:1)
$string = 'We are - (the + champions';
$split = preg_split('/[\-,\(,\+]/', $string);
答案 4 :(得分:0)
怎么样:
$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