PHP - 在foreach循环中递归替换字符串

时间:2013-09-07 05:03:05

标签: php arrays

这个工作:

示例有一些虚拟数组:$query

$query_string_parts

        foreach ($query as $query_keys => $query_string_parts)
        {
            $result['segments']['query'][$query_keys] = static::replace_regex_by_key($query_string_parts, ':alpha');

            $result['segments']['query'][$query_keys] = static::replace_regex_by_key($result['segments']['query'][$query_keys], ':digit');

            $result['segments']['query'][$query_keys] = static::replace_regex_by_key($result['segments']['query'][$query_keys], ':word');

            $result['segments']['query'][$query_keys] = static::replace_regex_by_key($result['segments']['query'][$query_keys], ':alphanum');

        }

另一方面,关注BLA

   $bla = somethingfunction($bla, 'case0');
   $bla = somethingfunction($bla, 'case1');
   $bla = somethingfunction($bla, 'case2');
   $bla = somethingfunction($bla, 'case3');

这段代码很乱,而且不干净!我不想这样。

正则表达式替换是:

`

private static $regex_replace = array(':word' => '/^[\w]*$/',
                                      ':digit' => '/^[\d]*$/',
                                      ':alpha' => '/^[a-zA-Z]*$/',
                                      ':alphanum' => '/^[a-zA-Z0-9]*$/'
                                      );


private static function replace_regex_by_key($input, $regex_loop_key)
{
    return preg_replace('/'.$regex_loop_key.'/', static::$regex_replace[$regex_loop_key], $input);
}`

结果(好的!):

在:

array(7) {
  [0]=>
  string(22) ":alpha:digit"
  [1]=>
  string(3) "abc"

在:

array(7) {
  [0]=>
  string(22) "/^[a-zA-Z]*$//^[\d]*$/"
  [1]=>
  string(3) "abc"

BUT!下面的代码很乱,想要从static::$regex_replace的数组调用并更改它:

下面的代码应该少一些代码,逻辑上,我不喜欢这样:

    $result['segments']['query'][$query_keys] = static::replace_regex_by_key($query_string_parts, ':alpha');

    $result['segments']['query'][$query_keys] = static::replace_regex_by_key($result['segments']['query'][$query_keys], ':digit');

    $result['segments']['query'][$query_keys] = static::replace_regex_by_key($result['segments']['query'][$query_keys], ':word');

    $result['segments']['query'][$query_keys] = static::replace_regex_by_key($result['segments']['query'][$query_keys], ':alphanum');

应该是:

    foreach (static::$regex_replace as $key) {      
    $result['segments']['query'][$query_keys] = static::replace_regex_by_key($query_string_parts, $key);
    }

但是,它不会回归,也许会使用operater &,但在课堂上最好的想法是什么?

1 个答案:

答案 0 :(得分:0)

所以,经过50分钟后仍然没有回答30次观看,我终于解决了这个问题。

没关系,解决为分离的功能,所以我打电话给:

foreach ($query as $query_keys => $query_string_parts)
            {
                $result['segments']['query'][$query_keys] = static::replace_segments($query_string_parts);
            }

函数调用为静态并执行:

private static function replace_segments($results)
{
    foreach (static::$regex_replace as $key => $val)
    {

        $results = static::replace_regex_by_key($results, $key);
    }

    return $results;
}