【问题标题】:PHP preg match exactlyPHP preg 完全匹配
【发布时间】:2017-02-03 14:41:51
【问题描述】:

我确实有以下预赛:

$search = 310850;

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

响应包含很多东西,但它包含310850 以及310850231085

信息:$response 包含一个 html 页面,其中包含许多包含 $search 的元素

我怎样才能确保我在310850而不是所有其他人上得到匹配?

编辑:

如何让字符 <> 出现在搜索旁边? 他们可以被包裹在ded123>number<blabla

【问题讨论】:

  • 不工作边界将匹配限制为整个单词?见this demo
  • 应该是这样,有什么问题?
  • @Toto 它也匹配所有比搜索词长或短的数字。我不想要那个
  • @maria: 不,见the demo/\b310850\b/ 既不匹配3108502 也不匹配31085
  • Strpos with exact matches 的可能重复项,那么答案就是您要寻找的内容

标签: php regex preg-match


【解决方案1】:
<?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 !

【讨论】:

  • 响应不是数组,它是整个 html 页面
  • 仔细看,它是一组测试用例,用于显示不同输入的输出
猜你喜欢
  • 1970-01-01
  • 2010-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-06
  • 1970-01-01
  • 2018-02-22
  • 1970-01-01
相关资源
最近更新 更多