Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find full words only in string

Tags:

php

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";
?>
like image 614
Sanjeev Chauhan Avatar asked Jan 17 '12 17:01

Sanjeev Chauhan


People also ask

Which function is used to search a full word within a given string?

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.

How do I search for a word in a string?

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.

How do you search for a word in regex?

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.


1 Answers

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];
}
like image 146
Ben Lee Avatar answered Sep 30 '22 17:09

Ben Lee