I would like to check if a string is in another string with comma separated. I've write some code and it work like this...
$find_number = '3'
$string_to_search = '1,3,124,12'
preg_match('/[^0-9]'.$find_number.'[^0-9]/', string_to_search);
//match
$find_number = '4'
$string_to_search = '1,3,124,12'
preg_match('/[^0-9]'.$find_number.'[^0-9]/', string_to_search);
//not match
Which is what I expected. The problem is that the first and last string can't recognized in this expression. What did I do wrong?
You need to make sure to check if there are no digits on both sides of the $find_number
, and that is why you need (?<!\d)
/ (?!\d)
lookarounds that do not consume text before and after the number you need to match allowing to check the first and last items. The [^0-9]
in your pattern are negated character class instances, that require a character other than a digit before and after the find_number. The lookarounds will just fail the match if there is a digit before ((?<!\d)
negative lookbehind) or after (with (?!\d)
negative lookahead) the find_number. See below:
$find_number = '3';
$string_to_search = '1,3,124,12';
if (preg_match('/(?<!\d)'.$find_number.'(?!\d)/', $string_to_search)) {
echo "match!";
}
See the PHP demo.
An alternative is to use explode
with in_array
:
$find_number = '3';
$string_to_search = '1,3,124,12';
if (in_array($find_number, explode(",", $string_to_search))) {
echo "match!";
}
See another PHP demo
You don't need regular expressions for such a simple task. If $find_number
doesn't contain the separator then you can enclose both $find_number
and $string_to_search
in separators and use function strpos()
to find out if $find_number
is present or not in $string_to_search
. strpost()
is much faster than preg_match()
.
$find_number = '3';
$string_to_search = '1,3,124,12';
if (strpos(",{$string_to_search},", ",{$find_number},") !== FALSE) {
echo("{$find_number} is present in {$string_to_search}");
} else {
echo("No.");
}
Wrapping $find_number
in separators is needed to avoid it finding partial values, wrapping $string_to_search
in separators is needed to let it find the $find_number
when it is the first or the last entry in $string_to_search
.