I have a regex which returns just numbers from string:
$str = "this is 1 str, 2";
$numb = preg_replace("/[^0-9]/","",$str);
echo $numb; // output: 12
But if string doesn't be containing number, then it will return nothing. Now I want it returns NULL if string isn't containing number. Something like this:
$str = "this is one str";
$numb = preg_replace("/[^0-9]/","",$str);
echo $numb; // current output:
// what I want: null
Note: That null isn't a string, it should be something like this: $numb = null;
How can I do that?
You can't do that just by using regex (since preg_replace returns a string or NULL if it encountered an error) . You actually need to check the variable and assign null if needed:
$numb = $numb ?: null;
You may return null on having empty values:
$str = "this is one str";
$numb = preg_replace("/[^0-9]/","",$str);
echo ( ! empty( $numb ) ? $numb : null );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With