Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/295.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_Preg Match - Fatal编程技术网

Php 正则表达式在两种情况下都使用一个?

Php 正则表达式在两种情况下都使用一个?,php,regex,preg-match,Php,Regex,Preg Match,好吧,这是绳子 $string = "123456789_some_0.png"; 我目前使用preg_match通过以下模式获得“123456789”: $pattern = "/[0-9]*/i"; 嗯,字符串有两种格式,我想对这种情况得出相同的结果: $string = "1234-123456789_some_0.png"; 并提出了“12345789”,仅从这两个案例中, 如何操作?假设要捕获所有后跟下划线的数字,可以使用以下方法: $strings = array("1234-

好吧,这是绳子

$string = "123456789_some_0.png";
我目前使用preg_match通过以下模式获得“123456789”:

$pattern = "/[0-9]*/i";
嗯,字符串有两种格式,我想对这种情况得出相同的结果:

$string = "1234-123456789_some_0.png";
并提出了“12345789”,仅从这两个案例中,
如何操作?

假设要捕获所有后跟下划线的数字,可以使用以下方法:

$strings = array("1234-123456789_some_0.png", "123456789_some_0.png");
foreach ($strings as $string) {
  preg_match("/([0-9]+)_/", $string , $matches);
  echo $matches[1], PHP_EOL; // 123456789
}

为什么不匹配第二个字符串中的
1234
?你想要符合的确切规则是什么?它必须有4个以上的数字?@JoãoSilva 1234只是一个例子,它实际上是一个变量,每次都用随机数改变是的,但在第二个字符串中,您要匹配的是
123456789
,而不是
1234
。为什么呢?因为
123456789
后面跟着一个下划线?@JoãoSilva-Yup。。下面的答案很有帮助,谢谢!