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.
Another way, that might be more efficient for laaaaaaaarge strings, is using a regexp:
$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
}
Notice guard ',' chars, they will help to deal with '13' magic '1, 2, 133' case.
Make sure you match the full number in the string, not just part of it.
function numberInList($num, $list) {
return preg_match("/\b$num\b/", $list);
}
$string = "8,7,13,14,16";
numberInList(13, $string); # returns 1
numberInList(8, $string); # returns 1
numberInList(1, $string); # returns 0
numberInList(3, $string); # returns 0
A simple string search should do if you are just checking to find existence of the string. I dont speak php but i think this is how it could be done.
$mystring = '8,7,13,14,16';
$findme = '13';
if (preg_match('/(?>(^|[^0-9])'.$findme.'([^0-9]|$))/', $mystring)) {
$result = "Yeah, that number is in there";
} else {
$result = "Sorry.";
}
精彩评论