Strpos with exact matches

前端 未结 2 1873
醉酒成梦
醉酒成梦 2020-12-11 22:48

I have a function in php which I would like to perform a simple search on a string, using a kw as the search phrase, and return true if found.

This is what I have no

相关标签:
2条回答
  • 2020-12-11 23:30

    You can use word boundaries \b:

    if (preg_match("/\b".preg_quote($kw_to_search_for)."\b/i", $search_strings[$i])) {
        // found
    }
    

    For instance:

    echo preg_match("/\bProfessional\b/i", 'Prof'); // 0
    echo preg_match("/\bProf\b/i", 'Prof');         // 1
    

    /i modifier makes it case insensitive.

    0 讨论(0)
  • 2020-12-11 23:41

    In my case I needed to match exactly professional when professional.bowler existed in the sentence.

    Where preg_match('/\bprofessional\b/i', 'Im a professional.bowler'); returned int(1).

    To resolve this I resorted to arrays to find an exact word match using isset on the keys.

    Detection Demo

    $wordList = array_flip(explode(' ', 'Im a professional.bowler'));
    var_dump(isset($wordList['professional'])); //false
    var_dump(isset($wordList['professional.bowler'])); //true
    

    The method also works for directory paths, such as when altering the php include_path, as opposed to using preg_replace which was my specific use-case.

    Replacement Demo

    $removePath = '/path/to/exist-not' ;
    $includepath = '.' . PATH_SEPARATOR . '/path/to/exist-not' . PATH_SEPARATOR . '/path/to/exist';
    $wordsPath = str_replace(PATH_SEPARATOR, ' ', $includepath);
    $result = preg_replace('/\b' . preg_quote($removePath, '/'). '\b/i', '', $wordsPath);
    var_dump(str_replace(' ', PATH_SEPARATOR, $result));
    //".:/path/to/exist-not:/path/to/exist"
    
    $paths = array_flip(explode(PATH_SEPARATOR, $includepath));
    if(isset($paths[$removePath])){
        unset($paths[$removePath]);
    }
    $includepath = implode(PATH_SEPARATOR, array_flip($paths));
    var_dump($includepath);
    //".:/path/to/exist"
    
    0 讨论(0)
提交回复
热议问题