Yogesh Chauhan's Blog

Check If a String Contains a Specific Word in PHP

in PHP on May 6, 2020

We can use the PHP strpos() Function to do that.

The strpos() function finds the position of the first occurrence of a string inside another string.

Syntax:


strpos ( string $haystack , mixed $needle [, int $offset = 0 ] ) : int

In simple terms,


strpos(the string to loon into, the string to find, start point of search)

First two parameters are required and third one is optional.

Example to search a word:


<?php
$word = "Yogesh";
$searchInThisString = "This website is Yogesh Chauhan's Blog";
 
if(strpos($searchInThisString, $word) !== false){
    echo "word found";
    //add more logic if you want
} else{
    echo "word NOT found";
    //add more logic if you want
}
?>

Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
WordPress: How to find all posts from a custom post type with specific custom field?WordPressContainers 101: What are containers?MiscellaneousClearwater Seafoods – B2C in ChinaMiscellaneousHow to check if a link has http or https in it in JavaScript?JavaScriptWordPress: How to find all posts with a specific custom field value?WordPressWhat’s a page re-rendering in React?ReactHow different is Handling Events in React vs HTML DOM?ReactOOP, Class and Objects Strategies For Beginners (PHP)PHPHow to create a Horizontal Scroll on button click using JavaScript?JavaScriptHow to delete a local and a remote Git branches?MiscellaneousComponents and Props in ReactReactHow to add and remove list items using JavaScript?JavaScript