1

这工作:

示例有一些虚拟数组:$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"

但!下面的代码很混乱,想要从数组中调用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);
    }

但是,它不会递归返回,也许使用操作符&但在课堂上什么是最好的主意?

4

1 回答 1

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;
}
于 2013-09-07T05:53:37.683 回答