正则表达式将abcd转换为(a(b(c(d))))

时间:2012-09-28 21:08:21

标签: php regex preg-replace pcre

我正在使用PHP的preg_replace,并尝试转换字符串

abcd

(a(b(c(d))))

这是我得到的最好的:

preg_replace('/.(?=(.*$))/', '$0($1)', 'abcd');
// a(bcd)b(cd)c(d)d()

甚至可以使用正则表达式吗?

编辑我刚刚在PCRE规范Replacements are not subject to re-matching中发现了这一点,所以我的原始方法无效。我想保留所有正则表达式,因为在我的实际用例中有一些更复杂的匹配逻辑。

4 个答案:

答案 0 :(得分:6)

怎么样:

preg_replace('/./s', '($0', 'abcd') . str_repeat(')', strlen('abcd'));

(这是否算作“正则表达式”?)

答案 1 :(得分:1)

您可以使用preg_match_all。但不确定你想要什么样的角色。所以我将举例说明所有角色:

$val = 'abcd1234';
$out = '';

if(preg_match_all('#.#', $val, $matches))
{
    $i = 0; // we'll use this to keep track of how many open paranthesis' we have
    foreach($matches[0] as &$v)
    {
        $out .= '('.$v;
        $i++;
    }
    $out .= str_repeat(")", $i);
}
else
{
    // no matches found or error occured
}

echo $out; // (a(b(c(d(1(2(3(4))))))))

也可以轻松进一步定制。

答案 2 :(得分:0)

这是我的方法=):

<?php
$arr = str_split("abcd");
$new_arr =  array_reverse($arr);

foreach ($new_arr as $a) {
    $str = sprintf('(%s%s)', $a, $str);
}
echo "$str\n";

?>

KISS不是吗? (几行:6)

答案 3 :(得分:0)

我选择了上述答案的组合:

preg_match_all('/./ui', 'abcd', $matches);
$matches = $matches[0];
$string = '('.implode('(', $matches).str_repeat(')', count($matches));
相关问题