Hey there! any question in your mind? Ask It Now!.

Popular Categories





How to check a string contains a specific word in php?

+4 votes
709 views
asked in Programming by Aman

here is  a string i.e $test = ‘india is great country’ ; Now i am checking india here like

 

if ($test contains ‘india’)

echo ‘pass’;

 

Now I want to discuss is that a correct way to use if statement which I have used above if ($test contains ‘india’) ?

 

Please give your opinions thanks!

 

5 Answers

+1 vote
answered by anonymous
if ( strpos( $test,'india' ) !== false ) {
    echo 'true';
}
commented by Kirill Smelov
For simple text rules you can use strpos (http://php.net/manual/ru/function.strpos.php) function. So your condition checking is going to be like this strpos($test, "india") !== false. For more complicated rules you can use preg_match (http://php.net/manual/ru/function.preg-match.php) function based on regular expressions.
0 votes
answered by anonymous
Tyr this :

$result = (preg_match('/(I|i)ndia/', $test) ? true : false);

echo $result;
0 votes
answered by anonymous
$test = ‘india is great country’;

if (stristr($test, 'india') !== false) echo 'pass';
0 votes
answered by nitin (810 points)
Convert the string you are searching in to lowercase, then use strpos or strstr. You can merge the above two steps if you do not want two distinct passes of the string. The docs themselves recommend using strpos/strstr over using a regex as they will be faster.
0 votes
answered by McCumskey
stripos does a case insensitive search. Its faster than any other method as it runs within the C code for PHP instead of using the regex parser which is slower.

One thing to always remember, if there is a built-in PHP function that can do a string manipulation for you, always use that before any regex option as it is always faster.

Related Questions

+2 votes
1 answer 138 views
+3 votes
1 answer 597 views
–1 vote
0 answers 108 views
+2 votes
3 answers 277 views
+1 vote
1 answer 84 views
+6 votes
2 answers 2,016 views

Not a Member yet?

Ask to Folks Login

My Account
159 Folks are online
0 members and 159 guest online
Your feedback is highly appreciated