dounao1856 2012-07-10 16:34
浏览 42
已采纳

PHP - preg_match来自关联数组的整个单词,使用stristr而不是preg_match

I am looping through an associative array and trying to match the whole word from the needle array into the haystack array. The following code works perfectly but returns too many results since it's matching any occurance of the string:

$result = array();
$name1 = array();
$name2 = array();
foreach($object->organizations as $o) {
    foreach($objectCrunch as $o2) {
        $name1 = $o->name;
        $name2 = $o2->name;

        if(stristr($name2, $name1)) {
            $result[] = $o2->permalink;
        }
    }
}

When I try the following code:

$result = array();
$name1 = array();
$name2 = array();
foreach($object->organizations as $o) {
    foreach($objectCrunch as $o2) {
        $name1 = $o->name;
        $name2 = $o2->name;

        $pattern = "'/\b" . $name2 . "\b/i'";

        if(preg_match($pattern, $name1)) {
            $result[] = $o2->permalink;
        }
    }
}

I get an empty array. Any help getting the last piece of code working would be great.

Thanks, Greg

  • 写回答

2条回答 默认 最新

  • dream198731 2012-07-10 16:45
    关注

    You are using two pairs of delimiters here:

    $pattern = "'/\b" . $name2 . "\b/i'";
                ||      
                1|
                 2
    

    Use either / or '.
    I'd say the single quotes are redundant and the result of hasty copy & pasting.

    Also, preg_quote for the content/word if it might contain either.


    So as Elias points out; The next pitfall is likely trying to use the long content variable as search parameter. This would have been an obvious error, if you didn't give your variables meaningless enumerated names.

    Only one of them is likely an actual word or name. The other should be called content or something:

        $word = $o->name;
        $textcontent = $o2->name;
    

    Use those henceforth.
    While at it, also fix the object property naming accordingly.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致