繁体   English   中英

从字符串中提取5或6位数字

[英]Extract 5 or 6 Digit Numbers from the string

我试图只从字符串中提取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));

Lookarounds和一个远程量词应该可以解决问题。

模式逻辑说找到5或6位数的序列,然后在匹配的数字之前和之后查看,以确保两侧都没有数字。

代码( 演示

$strings = [
    "21-114512",
    "test12345abcd",
    "12test123456testing",
    "123456",
    "1234",
    "12345a67890"
];
function extract_numbers($string)
{
   return preg_match_all('/(?<!\d)\d{5,6}(?!\d)/', $string, $match) ? $match[0] : [];
}
foreach ($strings as $string) {
    var_export(extract_numbers($string));
    echo "\n---\n";
}

输出:

array (
  0 => '114512',
)
---
array (
  0 => '12345',
)
---
array (
  0 => '123456',
)
---
array (
  0 => '123456',
)
---
array (
)
---
array (
  0 => '12345',
  1 => '67890',
)
---

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM