正则表达式匹配数字中的数字

时间:2014-04-24 07:09:05

标签: php regex

这是验证电话号码的正则表达式。适用于各种数字,如1223534345等。

/(?:\((\+?\d+)?\)|(\+\d{0,3}))? ?\d{2,3}([-\.]?\d{2,3} ?){3,4}/

片段:

foreach ($words as $word){

    $arrwords = array(0=>'zero',1=>'one',2=>'two',3=>'three',4=>'four',5=>'five',6=>'six',7=>'seven',8=>'eight',9=>'nine');
    preg_match_all('/[A-za-z]+/', $text, $matches);
    $arr=$matches[0];
    foreach($arr as $v)
    {
       $text= str_replace($v,array_search($v,$arrwords),$text);
    }

    $pattern = '/(?:\((\+?\d+)?\)|(\+\d{0,3}))? ?\d{2,3}([-\.]?\d{2,3} ?){3,4}/';
    preg_match_all($pattern, $text, $matches, PREG_OFFSET_CAPTURE );
    $this->pushToResultSet($matches);
}

但我想添加这样的漏洞:

1223five34345,也应将其视为1223534345,并应进行过滤。这可能吗?

1 个答案:

答案 0 :(得分:2)

说明:

映射$arrwords中显示的所有单词,现在执行preg_match_all()以检查所有单词的出现次数。抓住他们的阵列。现在循环该数组并检查$arrwords数组中是否存在该值,如果找到则将该键映射到该字符串。

<?php
$arrwords = array(0=>'zero',1=>'one',2=>'two',3=>'three',4=>'four',5=>'five',6=>'six',7=>'seven',8=>'eight',9=>'nine');
$str='I won total five prize';
preg_match_all('/[A-za-z]+/', $str, $matches);
$arr=$matches[0];
foreach($arr as $v)
{
    $v = strtolower($v); //<--- Fail safe !!
    if(in_array($v,$arrwords))
    {
    $str = str_replace($v,array_search($v,$arrwords),$str);
    }
}
echo $str; //I won total 5 prize

现在,您可以使用正则表达式验证此$str