How to find full words only in string
<?php
$str ="By ILI LIKUALAYANA MOKHTAKUALAR AND G. SURACH Datuk Dr Hasan Ali says he has no intention of joining Umno. Pic by Afendi Mohamed KUALA LUMPUR: FORMER Selangor Pas commissioner Datuk Dr Hasan Ali has not ruled out the possibility of returning to Pas' fold";
$search ="KUALA";
?>
You can use the SEARCH and SEARCHB functions to determine the location of a character or text string within another text string, and then use the MID and MIDB functions to return the text, or use the REPLACE and REPLACEB functions to change the text.
To find a word in the string, we are using indexOf() and contains() methods of String class. The indexOf() method is used to find an index of the specified substring in the present string. It returns a positive integer as an index if substring found else returns -1.
To run a “whole words only” search using a regular expression, simply place the word between two word boundaries, as we did with ‹ \bcat\b ›. The first ‹ \b › requires the ‹ c › to occur at the very start of the string, or after a nonword character.
To see if a particular word is in a string, you can use a regular expression with word boundaries, like so:
$str = "By ILI LIKUALAYANA MOKHTAKUALAR AND G. SURACH Datuk Dr Hasan Ali says he has no intention of joining Umno. Pic by Afendi Mohamed KUALA LUMPUR: FORMER Selangor Pas commissioner Datuk Dr Hasan Ali has not ruled out the possibility of returning to Pas' fold";
$search = "KUALA";
if (preg_match("/\b$search\b/", $str)) {
// word found
}
Here \b
means "boundary of a word". It doesn't actually match any characters, just boundaries, so it matches the edge between words and spaces, and also matches the edges at the ends of the strings.
If you need to make it case-insensitive, you can add i
to the end of the match string like this: "/\b$search\b/i"
.
If you need to know where in the string the result was, you can add a third $matches
parameter which gives details about the match, like this:
if (preg_match("/\b$search\b/", $str, $matches)) {
// word found
$position = $matches[1];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With