Search code examples
phpregexpreg-match

Preg_Match exact Word and Output the Word from String Text


How to output the match word case insensitive? PHP Code:

if(preg_match("/(?i)(?<= |^)" . $Word . "(?= |$)/", $String)) {
 // If Exact Word is Match Case Insensitive
}

Example my string is: Hello there, the Video was funny.

I want to get " Video " from String but because my PHP preg_match is case insensitive and i'm looking for " video " i need to get the output " Video " from the string to.

Another String Example: Hello there, the vIDeo was funny To get the output " vIDeo " from the string.

Another String Example: Hello there, the vIDeowas funny. This String don't need to output " vIDEOwas " because is not match exact word.

I need this script so i can see the way exact words is found on string after search them.


Solution

  • You can use the third argument to preg_match() to fetch the matches; in your case there will be at most one matched pattern:

    $body = 'Hello there, the Video was funny';
    $search = 'video';
    
    if (preg_match('/\b' . preg_quote($search, '/') . '\b/i', $body, $matches)) {
      print_r($matches[0]); // Video
    }
    

    A few other changes to your code:

    1. Always use preg_quote() if you don't know where the search term comes from.
    2. I use the /i modifier instead of (?i)
    3. Instead of look-behind and look-ahead assertion, I use the zero width \b assertion instead.