0

私はこれを内の関数にしていpreg_replace()ます。

私はそれを次のように使用しています:

$pattern[] = "/\[test\](.*?)\[\/test\]/is";
$replace[] = $this->test('$1');

$content = preg_replace($pattern, $replace, $content);

次に、関数test()は送信された値を出力します。ただし、値は常にだけです$1が、からのコンテンツである必要があります[test]...[/test]

これを行う方法はありますか?

4

3 に答える 3

3

test()の値を受け取ることはなく、$1常にリテラル文字列を取得します"$1"。を実行$this->test()すると、関数が呼び出さtest()れ、括弧に入れられたものが引数として受け取られます。

実行されるまでtest()に、正規表現はまだ評価されていません。あなたがしなければならないでしょう:

$pattern = "/\[test\](.*?)\[\/test\]/is";
$content = $this->test( preg_replace( $pattern, '$1', $content));

これによりtest()、の値を受け取ることになります$1。そうでなければ、あなたは必要になるでしょうpreg_replace_callback()

$pattern[] = "/\[test\](.*?)\[\/test\]/is";
$content = preg_replace($pattern, function( $match) { 
    return $this->test( $match[1]); 
}, $content);
于 2013-02-17T17:57:37.673 に答える
3

$this->test最初のサブパターンの対応する一致した文字列を持つメソッドの戻り値で一致を置き換えたい場合は、preg_replace_callback代わりにラッパー関数を使用する必要があります。

$pattern = "/\[test\](.*?)\[\/test\]/is";
$replace = function($match) use ($this) { return $this->test($match[1]); };
$content = preg_replace_callback($pattern, $replace, $content);
于 2013-02-17T17:59:26.233 に答える
-2

一重引用符はリテラル文字列を意味します。

だから'$1'戻ってくる$1

while"$1"は、格納されている正規表現キャプチャ値$1をその値に解釈します

于 2013-02-17T17:54:49.267 に答える