drbae3964 2015-02-27 03:51
浏览 416
已采纳

PHP strpos匹配多个干草堆中的所有针

I want to check if ALL words from $words exist in one or more $sentences, word order is not important.

Words will only contain [a-z0-9].

Sentences will only contain [a-z0-9-].

My code so far, it almost work as expected:

$words = array("3d", "4");
$sentences = array("x-3d-abstract--part--282345", "3d-speed--boat-430419", "beautiful-flower-462451", "3d-d--384967");

foreach ($words as $word) {
    $sentences_found = array_values(array_filter($sentences, function($find_words) use ($word) {return strpos($find_words, $word);}));
}
print_r($sentences_found);

If you run this code here http://3v4l.org/tD5t5 , you'll get 4 results, but in reality it should be 3 results

Array
(
    [0] => x-3d-abstract--part--282345
    [1] => 3d-speed--boat-430419
    [2] => beautiful-flower-462451   // this one is wrong, no "3d" in here, only "4"
    [3] => 3d-d--384967
)

How can I do this?

Also is there any better way to do this than strpos?

Regex?

Regex is maybe slow for this job because sometimes there will be 1000's of $sentences (don't ask why).

  • 写回答

1条回答 默认 最新

  • dongniaoli1822 2015-02-27 05:19
    关注

    You could use an intersection of found sentences per word:

    $found = array();
    
    foreach ($words as $word) {
        $found[$word] = array_filter($sentences, function($sentence) use ($word) {
            return strpos($sentence, $word) !== false;
        });
    }
    
    print_r(call_user_func_array('array_intersect', $found));
    

    Or, approach from $sentences:

    $found = array_filter($sentences, function($sentence) use ($words) {
        foreach ($words as $word) {
            if (strpos($sentence, $word) === false) {
                return false;
            }
        }
        // all words found in sentence 
        return true;
    });
    
    print_r($found);
    

    One important thing to mention is that your search criteria was wrong; instead of strpos($sentence, $word) you should explicitly compare against false, otherwise you will miss a match at the start of a sentence.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?