[英]PHP: preg_match_all consider two equal matches as one
我想從字符串(實際上是HTML)中提取一些數據。 我搜索了一下,發現preg_match_all。 問題是,如果存在兩個相等的匹配項,則該函數會將它們視為兩個,並為兩者留出空間。 我的代碼,代碼的輸出和代碼的預期輸出將清楚地說明。
<?php
$html = "
<!doctype html>
<html lang=\"en\">
<head>
<meta charset=\"UTF-8\">
<title>Document</title>
</head>
<body>
<img src=\"[profileLink@user:0]\" />
<img src=\"[profileLink@user:0]\" />
</body>
</html>
";
$regex = "/\[(.*?)@(.*?)\]/";
preg_match_all($regex, $html, $matches);
var_dump($matches);
?>
輸出:
array (size=3)
0 =>
array (size=2)
0 => string '[profileLink@user:0]' (length=20) // It looks ok
1 => string '[profileLink@user:0]' (length=20) // Don't want it.
1 =>
array (size=2)
0 => string 'profileLink' (length=11) // It looks ok
1 => string 'profileLink' (length=11) // Don't want it.
2 =>
array (size=2)
0 => string 'user:0' (length=6) // It looks ok
1 => string 'user:0' (length=6) // Don't want it.
預期產量:
array (size=3)
0 =>
array (size=1)
0 => string '[profileLink@user:0]' (length=20)
1 =>
array (size=1)
0 => string 'profileLink' (length=11)
2 =>
array (size=1)
0 => string 'user:0' (length=6)
使用preg_match
而不是preg_match_all
,結果將是:
array(3) {
[0]=>
string(20) "[profileLink@user:0]"
[1]=>
string(11) "profileLink"
[2]=>
string(6) "user:0"
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.