Check if a string contains a particular word using PHP

In this PHP related post, we are going to see how to check if a string contains a particular word inside it. We are going to do it in PHP. We may be needed to find the availability of a particular word in an article in PHP programming language.

We may want to check if the word available in the string using case sensitive or case insensitive.

Below is the example to find the word from the string:

<?php
    $str = 'I love programming in PHP';

    // Get the position of the word
    $word_pos = strpos($str, 'PHP');

    // Check if it returns the position
    if ($word_pos != "") {
    	echo "Found";
    } else {
    	echo "Not Found";
    }
?>

In the above example, we have used the PHP strpos() function which finds the position of our word in the string and returns the position of that word. If the word is not available inside the string, it will return nothing. So we have checked the condition if the position returns or not because if there is a position of the word, it means the word found in the string.

Remove duplicate values from an array in PHP

Execute and calculate string as a mathematical equation in PHP

The above example has done with case-sensitive. Now below is the example where we will check if the word available in the string or not with case-insensitive:

<?php

    $str = 'I love programming in PHP';
    // Find the position of the word with case-insensitive
    $word_pos_ci = stripos($str, 'phP');
    // Check if position found
    if ($word_pos_ci != "") {
    	echo "Found";
    } else {
    	echo "Not Found";
    }

?>

We may be needed to find the word with the case-insensitive mode, so here we have also checked with case insensitive. In this case, we have used the stripos() PHP function which finds the position of the first occurrence of a case-insensitive substring in a string.

I hope you like this post and it will be helpful in your work.

Leave a Reply

Your email address will not be published. Required fields are marked *