Check if a string contains a certain number
I have a string
8,7,13,14,16
Whats the easiest way to determine if a given number is present in that string?
$numberA = "13";
$string = "8,7,13,14,16";
if($string magic $numberA){
$result = "Yeah, that number is in there";
} else {
$result = "Sorry.";
}
Looking for magic.
<?php
in_array('13', explode(',', '8,7,13,14,16'));
?>
…will return whether '13' is in the string.
Just to elaborate: explode turns the string into an array, splitting it at each ',' in this case. Then, in_array checks if the string '13' is in the resulting array somewhere.
另一种方式,对laaaaaaaarge字符串可能更有效,它使用正则表达式:
$numberA = "13";
$string = "8,7,13,14,16";
if(preg_match('/(^|,)'.$numberA.'($|,)/', $string)){
$result = "Yeah, that number is in there";
} else {
$result = "Sorry.";
}
if (strpos(','.$string.',' , ','.$numberA.',') !== FALSE) {
//found
}
注意守卫','字符,他们将帮助处理'13'魔法'1,2,133'的情况。
链接地址: http://www.djcxy.com/p/12866.html下一篇: 检查一个字符串是否包含某个数字