facebook icon twitter icon angle down linkedin icon youtube icon
Home > Blog > specific-word-in-string-php

How to check if a string contains a specific word in PHP

You can use the strpos() function to check a string for specific word.  It is used to find the occurrence of one string inside another one. Basically this function widely used in PHP version below 8. In PHP 8 you can also use str_contains() function.

 

In this article, I provided some example and brif explanation below.

Basic syntax

if (strpos('string', 'specific_word') != false){ echo 'true';}

str_contains('string', 'specific_word'){ echo 'true';}

We need to provide two parameters.

1. String: The first parameter should contain the string from where you want to find out the word.

2. Specific_word: In this parameter you should put a specific word which you want to find out from the string. 

Note: In the placement of parameters, you can use PHP variables.

Discussion and example: check string for a specific word

You should keep in mind that !== false, != false, === true, == true won’t give you the same result.

The function strpos() returns either the offset or the boolean false if the needle isn't found. As 0 is a valid offset and 0 is "falsey", you can't use simpler constructs like !strpos($string, 'word'). You can avoid this issue by always using strpos($string, 'word') > -1 to test for true. 

Example 1:

<?php
//input string
$string = 'Here is my example string'; 
//checking string
if (strpos($string, 'example') != false){
echo 'true';}
else{ echo 'false';}
?>

Output:

true

Example 2:

<?php
//input string
$string = 'Here is my example string'; 
//checking string
if (strpos($string, 'ample') != false){
echo 'true';}
else{ echo 'false';}
?>

Output:

true

This even showing the output ‘true.’ But why? In this string, there is no word ‘ample.’

If you are looking specifically for the word ‘ample’, then you need to check if there is a character or a space before and after the word.

Example 3:

<?php
//input string
$string = 'Here is my example string'; 
//checking string
if (strpos($string, ' ample ') != false){
echo 'true';}
else{ echo 'false';}
?>

Output:

false

Note: The both strpos() and str_contains() are case sensitive function.

Example 4:

<?php
//input string
$string = 'Here is my Example string'; 
//checking string
if (str_contains($string, ' example ')){
echo 'true';}
else{ echo 'false';}
?>

Output:

false

It returns the result false, because of case sensitiveness.

Tarikul islam

About Torikul islam

Torikul islam is a professional web developer and affiliate marketer. Join Torikul to learn how to start a website and operate it well. He started his Web Developement career from Bangladesh Association of Software and Information (BASIS) in 2015. Later he continiued his journey to expanding knowledge and sharing it with others.

Write a Comment

No comment yet