【问题标题】:Search a Number pattern搜索数字模式
【发布时间】:2013-08-06 05:33:35
【问题描述】:

我想从整个句子中搜索电话号码。在 PHP 的帮助下,它可以是具有 (122) 221-2172 或 122-221-2172 或 (122)-221-2172 等模式的任何数字,我不知道该数字存在于句子的哪个部分或我可以使用 substr。

【问题讨论】:

  • 学习正则表达式,伙计。
  • 可以显示电话号码的图案吗?
  • 这就是问题所在,因为电话号码可以是 123-123-1234 或 (123) 123-1234 或 (123)-123-1234 或 123 123 1234。随便
  • @sashkello。据我所知,我做不到,否则我不会在这里问这个问题。
  • @Soumya 我相信我的回复是解决你问题的方法,但是我不懂php...

标签: php string phone-number text-search


【解决方案1】:
 $text = 'foofoo 122-221-2172 barbar 122 2212172 foofoo ';
$text .= ' 122 221 2172 barbar 1222212172 foofoo 122-221-2172';

$matches = array();

// returns all results in array $matches
preg_match_all('/[0-9]{3}[\-][0-9]{6}|[0-9]{3}[\s][0-9]{6}|[0-9]{3}[\s][0-9]{3}[\s][0-9]{4}|[0-9]{9}|[0-9]{3}[\-][0-9]{3}[\-][0-9]{4}/', $text, $matches);
$matches = $matches[0];

var_dump($matches);

【讨论】:

    【解决方案2】:

    您可以使用regular expressions 来解决这个问题。不是 100% 使用 php 语法,但我想它看起来像:

    $pattern = '/^\(?\d{3}\)?-\d{3}-\d{4}/';
    

    ^ 说“以”开头
    \( 转义 (
    \(? 说 0 或 1 (
    \d{x} 准确地说是 x 数字

    您可能还想查看Using Regular Expressions with PHP

    【讨论】:

      猜你喜欢
      • 2012-08-30
      • 1970-01-01
      • 1970-01-01
      • 2010-09-21
      • 1970-01-01
      • 2020-04-30
      • 2021-11-24
      • 2012-11-01
      相关资源
      最近更新 更多