簡體   English   中英

preg_grep返回NULL

[英]preg_grep returns NULL

我有以下數組:

$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,並且可以正常工作。 我知道這一定是愚蠢的,但是我看不出問題出在哪里。

preg_grep()捕獲數組,而不是字符串。 您可能想使用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
)

應該能夠完全匹配使用

編輯如果您用換行符\\n char 連接所有源數組元素以形成單個
字符串,然后可以在該字符串上調用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 | $ )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM