Forum Moderators: coopster

Message Too Old, No Replies

Searching for whole word in string using php

searching for a whole word with in string of text

         

Tourex

8:52 am on May 17, 2005 (gmt 0)

10+ Year Member




Hi

As a newbie to PHP, can someone please help me with a frustrating small problem that has defeated my searches of the PHP manual.

I want to search a string of text for the occurrence of a certain word or set of words. Easy enough, but I only want to find occurences of whole words. For example, if I'm searching for "today's exam", I want to ignore "today's example".

Any thoughts please?

buriedUnderGround

9:28 am on May 17, 2005 (gmt 0)

10+ Year Member



i'd try using a regular expression to make sure that the phrase is only ever followed by a space or "." character which would mean that the word ended (ie: no extra letters after search string)

Birdman

10:57 am on May 17, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Or, you could split the text up into single words, then do an in_array():

$text = "your text";
$words = explode(" ", $text);
if(in_array("word") {print "word exists in text";}

Cheers

buriedUnderGround

2:20 pm on May 17, 2005 (gmt 0)

10+ Year Member



good idea, but if there was a lot of text your array might get big.

here's what you're looking for:
from : [php.net...]
<?php
/* The \b in the pattern indicates a word boundary, so only the distinct
* word "web" is matched, and not a word partial like "webbing" or "cobweb" */
if (preg_match("/\bweb\b/i", "PHP is the web scripting language of choice.")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}

if (preg_match("/\bweb\b/i", "PHP is the website scripting language of choice.")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
?>