Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/285.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.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,我想从单词“minimum”之前的字符串中获取第一个数字,前面是空格,后面不是“-”。例如: 不应与单词2-3、TT-89等匹配;(即,一个数字后接-和另一个数字或字母后接-和数字) 应与单词2-rolls匹配(即数字后跟-和字母) 我正在使用以下代码进行尝试: $str = "Red QQ-4555 White TT-789 Yellow Minimum order applies. This is a test"; $explodeByMinimumArray = preg_spli

我想从单词“minimum”之前的字符串中获取第一个数字,前面是空格,后面不是“-”。例如:

  • 不应与单词2-3、TT-89等匹配;(即,一个数字后接-和另一个数字或字母后接-和数字)
  • 应与单词2-rolls匹配(即数字后跟-和字母)
我正在使用以下代码进行尝试:

$str = "Red  QQ-4555 White  TT-789 Yellow Minimum order applies. This is a test";
$explodeByMinimumArray = preg_split("/minimum/i", str_replace(array( '(', ')' ), ' ', $str));   
preg_match_all('/\d+(?!-\d)/', $explodeByMinimumArray[0], $numberFromStringBeforeMinimumArray);  
print_r($numberFromStringBeforeMinimumArray);
这将返回
$numberfromstringbeforemimimumarray
,如下所示:

Array
(
    [0] => Array
        (
            [0] => 4555 
            [1] => 789
        )

)
但预期输出为空,因为QQ-4555和TT-789前面有一些字符


有人能帮我修一下吗?提前谢谢

您需要使用负数查找,以确保前面有字母/数字和
-
的数字不匹配:

(?<![\p{L}\d]-|\d)\d+(?!-\d)
(?
看

详细信息

  • (?-如果当前位置左侧紧跟着一个字母或数字,后面紧跟着
    -
    或一个数字,则匹配失败的负查找
  • \d+
    -1+位
  • (?!-\d)
    -如果存在一个
    -
    ,然后是当前位置右侧的一个数字,则会导致匹配失败的负前瞻
将给予

Array
(
    [0] => Array
        (
            [0] =>  123
        )

)

您可以使用多个lookaround断言来使用此正则表达式:

(?<=\s)\d+\b(?!-\d+)(?=.*Minimum)
(?试试看
(?<=\s)\d+\b(?!-\d+)(?=.*Minimum)