這是很簡單的。您正在使用preg_match
,它試圖找到一個發生給定模式,找到所有匹配use preg_match_all
。
以同樣的方式這兩種工作:$matches
陣列將具有分配到索引爲0(包括引號)全模式匹配,和基團(一個或多個)將被分配給所有後續索引(在這種情況下$matches[0]
將包含引號內的字符)。區別在於preg_match_all
將分配數組到上述索引,列出模式的每個匹配。
preg_match("/'([^]+)'/", $input, $matches);
var_dump($matches);
會給一個這樣的數組:
array(
"'wonderful'", //because the pattern mentions the ' chars
"wonderful" //because I'm grouping the chars inside the '
);
鑑於此代碼:
preg_match_all("/'([^']+)'/", $input, $matches));
爲您提供:
array (
//array of full matches, including the quotes
array (
'\'wonderful\'',
'\'stuck\'',
),
//array with groups
array (
'wonderful',
'stuck',
),
);
正如你可以看到on this live example
我簡化了一下你的表情,因爲你對「劃定的」感興趣,因此我匹配並組合每個非'
,後面跟着一個單引號,接下來是另一個單引號單引號。因此,你想要匹配的字符類只是[^']
...除了'
之外的任何字符。
您可以對此建議模式進行的後期微優化將使用與{1,}
類似的possessive quantifier++
。或者,如果您想匹配空字符串(如果找到''
),則可以使用*+
。所以
if (preg_match_all("/'([^']++)'/", $subject, $matches))
var_dump($matches);
應該做的伎倆
Kind'a猜測這裏(從來沒有使用PHP的),但我認爲你的版本會工作,如果你只是在最後添加全局標誌「〜」,即'〜 \'(。*?)\'〜g'並刪除最後一個')',我猜這是一個錯字(或者它根本沒有用)。 (此外,逃避'是沒有必要的。) – ClasG
嘿感謝指出')'是一個錯字.. – shivam
@ClasG:單引號_have_在這裏逃脫,因爲OP的模式字符串由單引號分隔。 ..和PHP的PCRE的實現沒有全局標誌,但有一個'preg_match_all'函數可以做同樣的事情 –