简体   繁体   中英

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.

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.

You can replace found match with $Word and then compare two strings

$String = 'Hello there, the Video was funny';
$Word = 'Video';
$s2 = preg_replace("/(?i)(?<= |^)" . $Word . "(?= |$)/", $Word, $String);

if ( $s2 === $String ) {
    echo "found";
}else {
    echo "NOT found";
}

Another solution

$String = 'Hello there, the Video was funny';
$Word = 'Video';
$s = explode(' ',$String);
foreach($s as $w) {
    if( $w === $Word) {
        echo $w;
        break;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM