Breaking

Tuesday, March 10, 2020

How to check if a string contains a specific word?

To check if a particular/specific word is present in the given string or not, PHP has provided an inbuilt strpos() function.

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

Where,

string $haystack - is the actual string to search in. (strictly string data type) | required
mixed $needle - is the string that needs to find in the string | required
int $offsest - when specified, the search of the needle in the string will start from that index  | Optional

Return -

FALSE if the needle was not found otherwise TRUE.

Let's use strpos() to get the clear idea -

$haystack = 'PHP is the best web development language';
$needle = 'development';

if(strpos($haystack, $needle)) {
    echo 'found';
} else {
    echo 'not found';
}

// output

found

Sometimes, the needle which we need to find in the string is present at the start of the string. If we use the same example then it will return as 'not found' because when we search for PHP then strpos() will return that strings index which is 0 and hence when we check it inside if condition then it will execute else part.

So, to solve this problem we need to modify the solution and always use this approach to avoid rework.

$haystack = 'PHP is the best web development language';
$needle = 'development';

if(false !== strpos($haystack, $needle)) {
    echo 'found';
} else {
    echo 'not found';
}

//output

found


Conclusion:

So, to make sure that, required string/word is present in the given string we can use strpos() function.


No comments:

Post a Comment