操纵数组以在不同的上下文中使用

时间:2014-06-08 06:24:37

标签: php arrays regex

我正在使用正则表达式匹配模式。然后使用pushToResultSet推送匹配的结果。在这两种方式中,$resultSet会有类似的数组内容吗?类似的意思不是 有价值的,但格式。我想用第二种方式代替第一种代码。

更新:示例输入http://ideone.com/lIaP49

foreach ($words as $word){
    $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);
} 
return $resultSet;

现在我以另一种方式执行此操作并以类似方式推送数组。由于$matches是数组,此处$b也是数组,我猜两个代码都相似

$b = array();
$pattern = '/^(?:\((\+?\d+)?\)|(\+\d{0,3}))? ?\d{2,3}([-\.]?\d{2,3} ?){3,4}/';
foreach ($test as $value)
{
    $value = strtolower($value);
    // Capture also the numbers so we just concat later, no more string substitution.
    $matches = preg_split('/(\d+)/', $value, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
    if ($matches)
    {
        $newValue = array();
        foreach ($matches as $word)
        {
            // Replace if a valid word number.
            $newValue[] = (isset($arrwords[$word]) ? $arrwords[$word] : $word);
        }
        $newValue = implode($newValue);            
        if (preg_match($pattern, $newValue))
        {
                $b[] = $value;  
            $this->pushToResultSet($b);
        }
    }
}       
//print_r($b);
return $resultSet;

更新 我想用问题中的第二个代码替换的实际代码:

<?php
class Phone extends Filter{
    function parse($text, $words)
    {   
        $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)
        {
            $v = strtolower($v);
            if(in_array($v,$arrwords))
            {
            $text= str_replace($v,array_search($v,$arrwords),$text);
            }
        }
        //$resultSet = array();
        $l = strlen($text);
        foreach ($words as $word){
            $pattern = '/^(?:\((\+?\d+)?\)|(\+\d{0,3}))? ?\d{2,3}([-\.]?\d{2,3} ?){3,4}/';
            preg_match_all($pattern, $text, $matches, PREG_OFFSET_CAPTURE );
            //print_r($matches);
        }
        //print_r($matches);
        $this->pushToResultSet($matches);
        return $resultSet;
    }   
}

1 个答案:

答案 0 :(得分:0)

运行两个代码后,在输出变量上运行PHP的var_dump函数。

如果打印输出与类似数组内容的定义相匹配,那么您的答案是。否则,您的回答是