开发者

How to split a string with multiple separators followed or not by whitespaces (mixed)?

I'm looking for something that acts just like explode but using more than one string separator, i.e.

+ - (

could all be separators.

For 开发者_运维技巧example, after "exploding" the following string:

$string = 'We are 3+4-8 - (the + champions'

I should get this as $string[0]:

['We are 3+4-8']

Is there any function that acts that way?


$string = 'We are - (the + champions';
$words = preg_split('@[\W]+@', $string)

With this you obtain [We, are, the, champions]

$string = 'We are - (the + champions';
$words = preg_split('/[\+\-\(]/', $string)

With this you preserve whitespaces obtaining ['We are', ' ', 'the', 'champions']; it would be necessary a trim.

 $string = 'We are 3+4-8 - (the + champions';
 $words = preg_split('/[\+\-] |[\(]/', $string)

With this, finally, you obtain ['We are 3+4+8', 'the', 'champions']. Trim is not necessary in this case.


Use preg_split() with a character class.

$chars = '+-(';
$regexp = '/[' . preg_quote($chars, '/') . ']/';
$parts = preg_split($regexp, $string);

Forgot to add that if you're trying to parse expressions such as search queries, preg_split() won't cut it and you'll need a full fledged parser. I think there must be one in the Zend Framework.


This will split your string by either -, +, or (

$result = preg_split(/[ \- ]|[ \+ ]|[(]/im, $string);
$i = 0;
foreach ($result as $match){ 
  $result[$i] = trim($match);
}


$string = 'We are - (the + champions';

$split = preg_split('/[\-,\(,\+]/', $string);


How about:

$str = 'We are 3+4-8 - (the + champions';
$res = preg_split('/\s+[+(-]\s+/', $str);
print_r($res);

output:

[0] => We are 3+4-8
[1] => (the
[2] => champions
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜