C0d1ng
C0d1ng

Reputation: 451

PHP If entire word is within string

How would i go about checking if an ENTIRE word is present within a string in php? I've found a few answere here on StackOverFlow:

if (preg_match($needle, $haystack))

another way:

if (strpos($haystack, $needle) !== false)

Both of these methods work to a certain extent, BUT these methods will also return true if $haystack includes only a portion of $needle, which is a problem..

For example if i try to check if $haystack contains the word "PartialWord" BUT i make $needle equal to "Partial"

$needle = "Partial";
$haystack = "PartialWord-random)exampletextfoo-blabla";
if (preg_match($needle, $haystack))

it will return true even though it should return false because $needle is equal to "Partial" & for it to return true $needle should be equal to "PartialWord".

Any suggestions?

Upvotes: 1

Views: 95

Answers (3)

Andreas
Andreas

Reputation: 23968

I think the simplest solution is to use preg_match

If (preg_match("/\s" . $SearchWord . "\s/", $haystack)){
      Echo "found";
}else{
      Echo "not found";
}

It will look for $SearchWord with a space on each side, which is as far as I know the definition of word.
So in your case it wil not match Partial of Partialword since there is no space in Partialword.

Upvotes: 2

Naga
Naga

Reputation: 2168

preg_match('/\b(express\w+)\b/', $needle, $haystack); // matches expression
preg_match('/\b(\w*form\w*)\b/', $needle, $haystack); // matches perform,
                                                     // formation, unformatted

Where:

\b is a word boundary
\w+ is one or more "word" character*
\w* is zero or more "word" characters

See the manual on escape sequences for PCRE.

Upvotes: 4

apokryfos
apokryfos

Reputation: 40730

The simplest solution would be:

$words= preg_split("/\W/", $haystack);
return in_array($needle, $words);

Where \W is any non-word character.

Upvotes: 3

Related Questions