Find string in string

By | 13 March, 2009

Like other people i’ve seen complaining about in the net, i keep forgetting how to do this.

There are several ways of doing this, but here’s a simple one:

$haystack = "Once upon a time, on a far away kingdom...";
$needle = "kingdom";
    echo "Word found.";
    echo "Couldn't find the word.";

The function strstr($haystack,$needle) is case sensitive in its search.

If it doesnt find the $needle, it will return false, otherwise returns the string from the first occurence of the needle to the end of the haystack text.

There’s also the function stristr($haystack,$needle) does case insensitive search.

Here are links to the manual:


Other alternatives (regEx, etc):

strrchr() – Find the last occurrence of a character in a string
substr() – Return part of a string
preg_match() – Perform a regular expression match