PHP preg完全匹配

时间:2017-02-03 14:41:52

标签: php regex preg-match

我确实有以下pregmatch:

$search = 310850;

if (preg_match("/\b$search\b/i", $response)) {
        echo "match !";
    } else {
        echo "NO MATCH";
    }

响应包含很多内容,但它包含310850以及310850231085

到info:$ response包含一个html页面,其中包含许多包含$ search

的元素

如何确保我在310850而不是所有其他人匹配?

编辑:

如何允许字符<>位于搜索旁边? 它们可以包裹在ded123>number<blabla

1 个答案:

答案 0 :(得分:0)

<?php

$search = 310850;

$responses = ["310850"," 310850 ", "0310850","3108501",

"<html>
<a href='google.com'>310850</a>
</html>
"];

function test($search, $response){
    echo $response,": ";
    if (preg_match("/([^0-9]+|^)$search([^0-9]+|$)/i", $response)) {
        echo "match !";
    } else {
        echo "NO MATCH";
    }
    echo "\n";
}

foreach($responses as $response){
    test($search, $response);
}

输出:

php -q a.php
310850: match !
 310850 : match !
0310850: NO MATCH
3108501: NO MATCH
<html>
<a href='google.com'>310850</a>
</html>
: match !