我有以下数组:
$data = array(
"Between 'Fluent, spontaneous, almost effortless flow' and 'Communicates spontaneously and reasonably fluently even in longer complex speech'",
"Between 'Good use of a fairly broad vocabulary range sometimes with gaps' and 'Good range of vocabulary used in their field and most general topics but with gaps'"
);
我试图将单引号的内容放入另一个数组中:
for($i = 0; $i < count($data); $i++){
if(preg_match("/^Between/", $data[$i])){
$pattern = "/(?:^|\s)'([^']*?)'(?:$|\s)/";
$candos_split = preg_grep($pattern, $data[$i]);
}
}
但是$ candos_split返回NULL,即使我已经测试了我的正则表达式,它也没有问题。我知道它一定是蠢事,但我看不出问题出在哪里。
答案 0 :(得分:0)
preg_grep()
greps数组,而不是字符串。您可能想要使用preg_match_all()
代替:
$data = array(
"Between 'Fluent, spontaneous, almost effortless flow' and 'Communicates spontaneously and reasonably fluently even in longer complex speech'",
"Between 'Good use of a fairly broad vocabulary range sometimes with gaps' and 'Good range of vocabulary used in their field and most general topics but with gaps'"
);
$pattern = "/(?:^|\s)'([^']*?)'(?:$|\s)/";
$matches = array();
foreach($data as &$line) {
if(preg_match_all($pattern, $line, $m))
$matches = array_merge($matches, $m[1]);
}
print_r($matches)
将返回:
Array
(
[0] => Fluent, spontaneous, almost effortless flow
[1] => Communicates spontaneously and reasonably fluently even in longer complex speech
[2] => Good use of a fairly broad vocabulary range sometimes with gaps
[3] => Good range of vocabulary used in their field and most general topics but with gaps
)
答案 1 :(得分:0)
应该可以在一切匹配中使用它
编辑如果您使用换行符\n
字符加入所有源数组元素以形成单个
然后你可以在那个字符串上调用match_all,你应该得到一个单独的数组
所有不同的引用项目。
# '/(?m)(?:^Between|(?!^)\G)[^\'\n]*[^\S\n]\'([^\'\n]*)\'(?=\s|$)/'
(?m) # Multi line mode
(?:
^ Between # 'Between'
| # or,
(?! ^ )
\G # Start at last match
)
[^'\n]* # Not ' nor newline
[^\S\n] # Non - newline wsp
'
( [^'\n]* ) # (1)
'
(?= \s | $ )