duanbei2914 2014-10-15 05:19
浏览 34
已采纳

PHP preg_match - 如果匹配则回显结果?

I'm trying to display hyperlinks to screen but only if a corresponding ID is recorded in a string.

<?php
function check($i, $s) {
    if (preg_match('/'.$i.'/',$test)) echo $s;
}

$test = "000,001,002,003,004,005";

check("001","<a href=''>This is in the test string - 001</a>");
check("003","<a href=''>This is in the test string - 003</a>");
check("006","<a href=''>This is in the test string - 006</a>");
check("020","<a href=''>This is in the test string - 020</a>");
?>

The desired output would be:

<a href=''>This is in the test string - 001</a>
<a href=''>This is in the test string - 003</a>

As they are the only two matches to the values in the string.

This isn't working.. Can you advise why and how to get it working.?

Thanks

  • 写回答

1条回答 默认 最新

  • dou47732 2014-10-15 05:24
    关注

    You have not defined the variable $test in the function. You could do for example,

    <?php
    function check($i, $s, $test) {
        if (preg_match('/'.$i.'/',$test)) echo $s;
    }
    
    $test = "000,001,002,003,004,005";
    
    check("001","<a href=''>This is in the test string - 001</a>", $test);
    check("003","<a href=''>This is in the test string - 003</a>", $test);
    check("006","<a href=''>This is in the test string - 006</a>", $test);
    check("020","<a href=''>This is in the test string - 020</a>", $test);
    ?>
    

    You should use error_reporting(E_ALL); when you develop, in that case you would have seen the following message:

    Notice: Undefined variable: test in ... on line ... 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部