dongshu7162 2016-04-30 07:18
浏览 43

找到句子的确切短语,而不是短语的路径

I have problem with search tool! I use strpos function to search $phrase_key in $sentence, and there are some wrong!

strpos($sentence , $phrase_key,  0)
$phrase_key = "on the"; 
$sentence1  = "i am sitting on the table"      // Good search
$sentence2  = "the book is on the floor"      // Good search  
$sentence3  = "create function theme to..."   // it not fine
  • on the is a path of function theme, and function theme is not phrase i need to find
  • Please tell me how to fix this or how to find the wrong search! thank you very much!
  • 写回答

1条回答 默认 最新

  • dongsi1954 2016-04-30 10:21
    关注

    You can use regular expression with word boundary \b metacharacter:

    if( preg_match( "~\b$phrase_key\b~", $sentence, $matches ) )
    {
        // matched string is now in $matches[0]
    }
    

    If you are interesting in substring position, use PREG_OFFSET_CAPTURE flag:

    if( preg_match( "~\b$phrase_key\b~", $sentence, $matches, PREG_OFFSET_CAPTURE ) )
    {
        // matched string is now in $matches[0][0]
        // matched string position is now in $matches[0][1]
    }
    

    <kbd>regex101 demo</kbd>


    评论

报告相同问题?