搜索数字模式


Search a Number pattern

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

 $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);

您可以使用正则表达式来解决此问题。php语法不是100%,但我想它看起来像:

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

^表示"以"开头
'(逃离(
'(?比如0或1 (
'd{x}说的正是x的数字

您可能还想查看使用正则表达式与PHP