php - How to set NULL if REGEX doesn't has any matches? -
i have regex returns numbers string:
$str = "this 1 str, 2"; $numb = preg_replace("/[^0-9]/","",$str); echo $numb; // output: 12 but if string doesn't containing number, return nothing. want returns null if string isn't containing number. this:
$str = "this 1 str"; $numb = preg_replace("/[^0-9]/","",$str); echo $numb; // current output: // want: null note: null isn't string, should this: $numb = null;
how can that?
you can't just using regex (since preg_replace returns string or null if encountered error) . need check variable , assign null if needed:
$numb = $numb ?: null;
Comments
Post a Comment