PHP

How to Check a PHP Variable for a Specific String or Word

By April 11, 2018 No Comments

Using the PHP function strpos() you can search a PHP variable to find any occurrence of one string inside of another.

For example, your string is “Hello World!” and you want to perform another action if the PHP variable has the word “Hello” in the string.  Here’s an easy way to accomplish this using the strpos() command.

$a = "Hello World";

if(strpos($a, 'Hello') !== false){
	echo 'true';
}else{
	echo 'false';
}

If the variable has the word “Hello” within the string it will echo the word “true” otherwise it will echo the word “false” on your page.  This can get a little tricky if you don’t understand what the strpos() command is returning.  We cannot use other operators such as:

!(strpos($a, 'Hello')

strpos() returns either the offset at which the needle string begins in the haystack or the boolean false if the needle is not found.  So keep this in mind.

Leave a Reply