1

正規表現を使用してタグから情報を抽出し、タグのさまざまな部分に基づいて結果を返そうとしています。

preg_replace('/<(example )?(example2)+ />/', analyze(array($0, $1, $2)), $src);

そのため、パーツを取得してanalyze()関数に渡しています。そこに着いたら、パーツ自体に基づいて作業を行いたいと思います。

function analyze($matches) {
    if ($matches[0] == '<example example2 />')
          return 'something_awesome';
    else if ($matches[1] == 'example')
          return 'ftw';
}

など。しかし、分析機能に到達する$matches[0]と、文字列 ' ' に等しくなります$0。代わりに$matches[0]、preg_replace() 呼び出しから後方参照を参照する必要があります。これどうやってするの?

ありがとう。

編集: preg_replace_callback() 関数を見ました。おそらくこれは私が探しているものです...

4

2 に答える 2

8

そんな使い方はできませんpreg_replace。おそらくpreg_replace_callbackが必要です

于 2009-07-30T05:56:14.340 に答える
0
$regex = '/<(example )?(example2)+ \/>/';
preg_match($regex, $subject, $matches);

// now you have the matches in $matches and you can process them as you want

// here you can replace all matches with modifications you made
preg_replace($regex, $matches, $subject);
于 2009-07-30T05:55:57.273 に答える