php compare string result
how do i compare the with if else statement. in mysql query i can use LIKE %
statement.
in mysql :
$db->query("SELECT * FROM treat WHERE tanning LIKE 'Pro Tan%'");
in php:
if($tanning == 'Pro Tan') :
ech开发者_如何学Co 'xxx';
else :
echo 'zzz';
endif
// output zzz
There are a variety of different comparison functions you can use, depending on how sophisticated you want to make your comparison. To find specifically a string that starts with "Pro Tan", you could do:
if (strpos($tanning, 'Pro Tan') === 0)
echo 'xxx';
Note the triple ===
, since if strpos
returns false
, that's not at all the same as returning 0
.
Assuming the result begins with the value, you can use strncmp
.
$foo = 'Pro Tan 6mins';
if (strncmp($foo,'Pro Tan', 7) === 0)
echo 'match';
For case-insensative, you can also use strncasecmp
.
You are looking for the strstr()
function in PHP, which allows you to search for a string within a string.
if(strstr($tanning, 'Pro Tan')):
echo 'xxx';
else :
echo 'zzz';
endif;
if(preg_match("/^Pro Tan/",$foo)) {....}
Other answers given will also work, but regular expressions using preg_match()
is more flexible and will continue to work with more complex matching.
(some will say that regex is slow, but in this case, since it's just matching a straight string anchored to the start, it's a very efficient query)
精彩评论