Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set NULL if REGEX doesn't has any matches?

Tags:

regex

php

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?

like image 444
stack Avatar asked Dec 28 '25 18:12

stack


2 Answers

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;
like image 184
Idos Avatar answered Dec 31 '25 09:12

Idos


You may return null on having empty values:

$str  = "this is one str";
$numb = preg_replace("/[^0-9]/","",$str);
echo ( ! empty( $numb ) ? $numb : null );
like image 25
Pmpr.ir Avatar answered Dec 31 '25 10:12

Pmpr.ir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!