繁体   English   中英

如何提取纯文本 PHP 的 9 位数字(电话号码)

[英]How to extract 9 digits (number phone) of the text plain PHP

你能帮我这样做吗:我有一个文本,其中有一个 9 位数字,我需要提取它以将其存储在一个变量中,数字总是以 9 开头

文本字符串示例:

Lorem ipsum dolor sit amet, consectetur. Integer ac tempor 123456789, et semper arcu. Maecenas vitae enim sed tortor 980202301 venenatis commodo. Fusce tincidunt volutpat bibendum. Cras vehicula ligula at urna vestibulum condimentum.

Praesent non blandit 45678910911, sed porta nulla. Phasellus eleifend, metus in consequat dictum, arcu nibh accumsan dolor, eget tristique eros massa et nisl. Anexo 4577 Phasellus congue consequat ante, nec nisi sed elit malesuada tempor.

我需要的数字总是以最初的 9 开头,并不总是在 position 中 1 或 2 是随机的,我使用的代码如下:

$str = "Lorem...";
$pattern = '/[0-9]{9}/';
if (preg_match($pattern, $str, $matches)){
echo $matches[0];
}

我得到的结果如下:123456789 正确的是:980202301

您可以使用

(?<!\d)9\d{8}(?!\d)

请参阅正则表达式演示 详情

  • (?<!\d) - 左边不允许有数字
  • 9 - 一个9字符
  • \d{8} - 任何一个数字
  • (?!\d) - 不允许紧靠右边的数字。

另请参阅PHP 演示

$str = 'Lorem ipsum dolor sit amet, consectetur. Integer ac tempor 123456789, et semper arcu. Maecenas vitae enim sed tortor 980202301 venenatis commodo. Fusce tincidunt volutpat bibendum. Cras vehicula ligula at urna vestibulum condimentum. 
Praesent non blandit 45678910911, sed porta nulla. Phasellus eleifend, metus in consequat dictum, arcu nibh accumsan dolor, eget tristique eros massa et nisl. Anexo 4577 Phasellus congue consequat ante, nec  nisi sed elit malesuada tempor.';
$pattern = '/(?<!\d)9\d{8}(?!\d)/';
if (preg_match_all($pattern, $str, $matches)){
  print_r($matches[0]);
}

Output:

Array
(
    [0] => 980202301
)

您可以更改您的模式,使其匹配以 9 开头的数字

$pattern = '/9[0-9]{8}/'

您还可以使用单词边界\b来防止部分单词匹配,并匹配9位和 8 位数字。

请注意preg_match只会找到第一个匹配项,如果您希望所有匹配项使用preg_match_all

\b9\d{8}\b

正则表达式演示| PHP 演示

$str = 'Lorem ipsum dolor sit amet, consectetur. Integer ac tempor 123456789, et semper arcu. Maecenas vitae enim sed tortor 980202301 venenatis commodo. Fusce tincidunt volutpat bibendum. Cras vehicula ligula at urna vestibulum condimentum. 
Praesent non blandit 45678910911, sed porta nulla. Phasellus eleifend, metus in consequat dictum, arcu nibh accumsan dolor, eget tristique eros massa et nisl. Anexo 4577 Phasellus congue consequat ante, nec  nisi sed elit malesuada tempor.';
$pattern = '/\b9\d{8}\b/';
if (preg_match($pattern, $str, $matches)){
    echo $matches[0];
}

Output

980202301

暂无
暂无

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

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