[英]Regex match a mac address without semi-columns
我試圖理解為什么下面的 function 返回奇怪的結果
<?
$string = "001122334 001122334455 0011 0011223344556677";
preg_match_all('/([a-fA-F0-9]){12}/', $str, $matches);
?>
我不明白為什么 001122334455 出現兩次,為什么 5 5 在那里。 我正在尋找沒有半列匹配的 MAC 地址
Output
Array
(
[0] => Array
(
[0] => 001122334455
[1] => 001122334455
)
[1] => Array
(
[0] => 5
[1] => 5
)
)
你的正則表達式
([a-fA-F0-9]){12}
,即一個hex char被捕獲到一個組中,然后再將該組的值重寫11次(全部在全部,12 次),所以最后一個十六進制字符被捕獲在第二個匹配子數組中(在您使用輸入字符串獲得的每個匹配項中,它是5
,因此,您的第二個數組中有兩個5
s)。001122334455
匹配, 001122334455
中的0011223344556677
也匹配。刪除捕獲括號並使用整個單詞匹配模式,例如
# Word boundaries
preg_match_all('/\b[a-fA-F0-9]{12}\b/', $str, $matches)
# Whitespace boundaries
preg_match_all('/(?<!\S)[a-fA-F0-9]{12}(?!\S)/', $str, $matches)
# Hex char boundaries
preg_match_all('/(?<![a-fA-F0-9])[a-fA-F0-9]{12}(?![a-fA-F0-9])/', $str, $matches)
請參閱PHP 演示
我認為您應該必須解析值的空間結尾。
$string = "001122334 001122334455 0011 0011223344556677";
preg_match_all('/([a-fA-F0-9]){12}\ /', $string, $matches);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.