+4 votes
885 views
in Programming by

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
by
if ( strpos( $test,'india' ) !== false ) {
    echo 'true';
}
by
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
by
Tyr this :

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

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

if (stristr($test, 'india') !== false) echo 'pass';
0 votes
by (1.3k 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
by
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.

Not a Member yet?

Ask to Folks Login

My Account

Your feedback is highly appreciated