我试图仅从字符串中提取5或6位数字。下面是我尝试过的代码,但与预期不符。
$str1 = "21-114512"; //it should return 114512
$str2 = "test12345abcd"; //it should return 12345
$str3 = "12test123456testing"; //it should return 123456
function extract_numbers($string)
{
preg_match_all('/\b[^\d]*\d{6}[^\d]*\b/', $string, $match);
return $match[0];
}
print_r(extract_numbers($str1));
答案 0 :(得分:3)
解决方法和远程量词应该可以解决问题。
模式逻辑说找到5或6位数字的序列,然后查看匹配的数字的前后,以确保两边都没有数字。
代码(Demo)
array (
0 => '114512',
)
---
array (
0 => '12345',
)
---
array (
0 => '123456',
)
---
array (
0 => '123456',
)
---
array (
)
---
array (
0 => '12345',
1 => '67890',
)
---
输出:
{{1}}