-1

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!
Vinoth Krishnan
  • 2,925
  • 6
  • 29
  • 34
hunghvq
  • 11
  • 3

1 Answers1

0

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]
}

regex101 demo


fusion3k
  • 11,568
  • 4
  • 25
  • 47