这工作:
示例有一些虚拟数组:$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);
}
但是,它不会递归返回,也许使用操作符&
但在课堂上什么是最好的主意?