▽1
●
tdoi ●50ポイント ベストアンサー |
こんな感じ?
<?php $str = <<< INPUT <html> <body> <br> <div>foo<br>foo</div> <div> <div>bar<br>bar</div> </div> <br> </body> </html> INPUT; $target = "<br>"; $format = "<br%02d>"; $index = 1; do { $tag = sprintf($format, $index); $count = 0; $str = preg_replace("/{$target}/s", $tag, $str, 1, $count); ++$index; } while ($count == 1); echo $str; ?>
そのまま実行すると、こんな出力が得られます。
<html> <body> <br01> <div>foo<br02>foo</div> <div> <div>bar<br03>bar</div> </div> <br04> </body> </html>
str_replaceで十分だと思ったんですが、str_replaceにはlimit指定できないんですね?。
何かの参考になれば。
コールバック関数を使った例を作ってみました
<?php $text = 'aaa<br>bbb<br>ccc<br>ddd<br>eee'; $count = 0; echo preg_replace_callback('!(<br)(.?>)!', create_function('$matches','global $count; $count++; return $matches[1] . sprintf("%02d", $count) . $matches[2];'), $text);
こんな感じでしょうか。
<?php $num = 0; $txt = <<<DATA_TEXT A<br> B<br> C<br> D<br><br> E<br> DATA_TEXT; echo preg_replace_callback( '|(<br)(>)|', create_function ( '$match', 'global $num; $num += 1; return $match[1] . sprintf("%02d", $num) . $match[2];' ), $txt); ?>
ideone.com で、動作の確認をしています。
http://ideone.com/hY3Qa
実は、あまり PHP を知りません (^^;
なので、先程のコードを書くのは、マニュアルと首っ引きです。
参照したのは、PHP Manual の以下のページで、参照した順番に並べてます。
・PHP: preg_replace_callback - Manual
・PHP: 文字列 - Manual
・PHP: 変数のスコープ - Manual
・PHP: sprintf - Manual
やっぱり、基本はマニュアルだと思いますよ。
PHP のは、サンプルコードもいっぱい載ってますし。