1

这是我的字符串:

$myString = "first second third,el forth, fiveeee, six";

我想捕捉的是:

first
second
third
el forth
fiveeee
six

这是我尝试在 preg_split 中使用正则表达式的方法:

 $myPattern = "[\s,]";

问题是这会分别捕获“el”和“forth”..

我怎样才能欺骗它来捕获el?

编辑:

我不清楚..我想将 el 作为单个数组元素捕获..因为 EL 太短了..我认为它是一个单词。像:

EL CLASSICO,SOMETHING DIFFERENT,SOMETHINGELSEHERE SOMEMORETEXT应该:

* `EL CLASSICO`
* `SOMETHING DIFFERENT`
* `SOMETHINGELSEHERE`
* `SOMEMORETEXT`

它们应该用空格或逗号分隔,但如果有 EL 或 LE 之类的东西,则应忽略。

4

3 回答 3

2

问题编辑后没有好的解决方案,igrone

只是str_replace( ',' , ' ' , $myString)最终str_replace( ' ', ' ' , $myString)避免双空格或:

preg_replace( '@, ?' , ' ' , $myString)

于 2013-01-24T18:56:50.143 回答
1
<?php
$myString = "first second third,el forth,del fiveeee,six,six seven,four six";
$myPattern = "/\s*,\s*|(?<=[^\s,]{4})[\s,]+/";

print_r(preg_split($myPattern, $myString));
?>

生产

[0] => first
[1] => second
[2] => third
[3] => el forth
[4] => del fiveeee
[5] => six
[6] => six seven
[7] => four
[8] => six

(?<=[^\s,]{4}) is a positive look-behind assertion. It is only successful if preceded by four non-separator characters (but it does not match the characters themselves, it only checks that they exist). This allows it not to split if the previous word was too short. But it will always split if the separator includes a comma -- that's what \s*,\s*| is for.

于 2013-01-24T19:09:09.877 回答
0
implode(' ', preg_split('/,\s*/', $myString));
于 2013-01-24T18:57:45.607 回答