How to check php string contains a specific word

How to check php string contains a specific word, If you want to check for specific string in a word then You can use the strpos function which is used to find the occurrence of one string inside other. Here in this example I’m creating a variable with some words, I’m checking that variable with a specific word using string position PHP function. strpos is case sensitive, if you want case-insensitive sub-string then use stripos PHP function.

Example of How to check php string contains a specific word

Simple usage of strpos function for searching a string in a specific word. If you use this below code you will get basic idea why we are using strpos function, strpos will find’s the position of the first occurrence of a sub-string in a string. In this below code it find’s the numeric position of the first occurrence.

<?php
$var = "this is working?";
echo strpos($var,'working');

This is the code to check php string contains a specific word.

<?php
$var = "this is working?";
if (strpos($var,'working')) {
    echo 'Word found';
}else{
	echo "Not found";
}

But, you should know something while using strpos PHP function: if you are searching for “welcome” word inside a this string “this isworking?”, then the strpos function will return successful string position of “welcome”, in that string “welcome” was found, but it’s not a separate word. This will become a problem if you want to search for separate word in that string. If you want to overcome this problem use a space before string like this ” welcome”.

Example of How to check php string contains a specific word – case-insensitive

strpos function is case sensitive, if you are searching for case insensitive words then use stripos PHP function. You can use this below code.

<?php
$var = "this is Working?";
if (stripos($var,'working')) {
    echo 'Word found';
}else{
	echo "Not found";
}

Vivek Vengala
 

Vivek Vengala is a Online Entrepreneur, Web Developer from Hyderabad India.

Click Here to Leave a Comment Below 0 comments

Leave a Reply:

x

Join My Facebook Group to Receive Coding Tutorial for Free

email-subsribe