Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如果正则表达式不';有火柴吗?_Php_Regex - Fatal编程技术网

Php 如果正则表达式不';有火柴吗?

Php 如果正则表达式不';有火柴吗?,php,regex,Php,Regex,我有一个正则表达式,它只返回字符串中的数字: $str = "this is 1 str, 2"; $numb = preg_replace("/[^0-9]/","",$str); echo $numb; // output: 12 但若字符串不包含数字,那个么它将不返回任何内容。现在,如果字符串不包含数字,我希望它返回NULL。大概是这样的: $str = "this is one str"; $numb = preg_replace("/[^0-9]/","",$str); echo

我有一个正则表达式,它只返回字符串中的数字:

$str  = "this is 1 str, 2";
$numb = preg_replace("/[^0-9]/","",$str);
echo $numb; // output: 12
但若字符串不包含数字,那个么它将不返回任何内容。现在,如果字符串不包含数字,我希望它返回
NULL
。大概是这样的:

$str  = "this is one str";
$numb = preg_replace("/[^0-9]/","",$str);
echo $numb; // current output:
            // what I want: null
注意:如果
null
不是字符串,它应该是这样的:
$numb=null

我该怎么做呢?

您不能仅仅通过使用regex来实现这一点(因为
preg\u replace
在遇到错误时返回字符串或NULL)。如果需要,您实际上需要检查变量并分配
null

$numb = $numb ?: null;

如果值为空,则可以返回null:

$str  = "this is one str";
$numb = preg_replace("/[^0-9]/","",$str);
echo ( ! empty( $numb ) ? $numb : null );

这不是您正在寻找的纯正则表达式解决方案,但这里有一个解决方法,可以使用
filter\u var

定义一个函数:

function isint($val) {
   $i=filter_var($val, FILTER_SANITIZE_NUMBER_INT);
   return empty($i) ? NULL : $i;
}
然后将其用作:

var_dump( filter_var('Doe, Jane123 Sue', FILTER_CALLBACK, array('options' => 'isint')) );
//=> string(3) "123"

var_dump( filter_var('Doe, Jane Sue', FILTER_CALLBACK, array('options' => 'isint')) );
//=> NULL

如果为空,则为其分配null?
$numb=strlen($numb)==0?空:$numb?@Idos是的,没错。。。!(顺便说一句,我不想使用if statemtn)
if(empty($numb))$numb=null哦,我明白了,也有,但似乎你无论如何都需要一个正则表达式来获取数字;)