12

とても簡単です。preg_replace()PHP の名前付き後方参照のサポートに関して決定的なものを見つけることができないようです。

// should match, replace, and output: user/profile/foo
$string = 'user/foo';
echo preg_replace('#^user/(?P<id>[^/]+)$#Di', 'user/profile/(?P=id)', $string);

(?P=name)これは些細な例ですが、この構文が単にサポートされていないのではないかと思っています。構文上の問題、または存在しない機能ですか?

4

4 に答える 4

14

それらは存在します:

http://www.php.net/manual/en/regexp.reference.back-references.php

preg_replace_callback を使用:

function my_replace($matches) {
    return '/user/profile/' . $matches['id'];
}
$newandimproved = preg_replace_callback('#^user/(?P<id>[^/]+)$#Di', 'my_replace', $string);

またはさらに速い

$newandimproved = preg_replace('#^user/([^/]+)$#Di', '/user/profile/$1', $string);
于 2011-03-10T03:38:59.313 に答える
7

preg_replace名前付き後方参照をサポートしていません。

preg_replace_callback名前付き後方参照をサポートしていますが、PHP 5.3 以降では、PHP 5.2 以下では失敗することが予想されます。

于 2011-03-10T03:41:07.243 に答える
2

preg_replace名前付きサブパターンはまだサポートされていません。

于 2011-03-10T03:40:52.440 に答える
0

これを使用できます:

class oreg_replace_helper {
    const REGEXP = '~
(?<!\x5C)(\x5C\x5C)*+
(?:
    (?:
        \x5C(?P<num>\d++)
    )
    |
    (?:
        \$\+?{(?P<name1>\w++)}
    )
    |
    (?:
        \x5Cg\<(?P<name2>\w++)\>
    )
)?
~xs';

    protected $replace;
    protected $matches;

    public function __construct($replace) {
        $this->replace = $replace;
    }

    public function replace($matches) {
        var_dump($matches);
        $this->matches = $matches;
        return preg_replace_callback(self::REGEXP, array($this, 'map'), $this->replace);
    }

    public function map($matches) {
        foreach (array('num', 'name1', 'name2') as $name) {
            if (isset($this->matches[$matches[$name]])) {
                return stripslashes($matches[1]) . $this->matches[$matches[$name]];
            }
        }
        return stripslashes($matches[1]);
    }
}

function oreg_replace($pattern, $replace, $subject) {
    return preg_replace_callback($pattern, array(new oreg_replace_helper($replace), 'replace'), $subject);
}

\g<name> ${name} or $+{name}その後、replace ステートメントで参照として使用できます。

cf ( http://www.rexegg.com/regex-disambiguation.html#namedcapture )

于 2015-05-12T16:48:12.817 に答える