2017-04-26 8 views
-2

コード例事前に使用置き換える機能が

$str = "some text <cs> some text </cs> some text <cs> some text </cs> some text <cs> some text </cs>"; 
$str = str_replace("<cs>", <textarea id="codeBlock">, $str); 
$str = str_replace("</cs>", </textarea>, $str); 

は、今の問題は、それがすべて<cs><textarea id="codeBlock">に変換し、私が欲しいのは$strの最初の<cs>id="codeBlock-2"になるだろうid="codeBlock-1"秒を取得する必要がありますということですされていること等々。

+3

'str_replace'は、単純な文字列の置き換えです。このような場合、これまでに行われた置換の数に基づいて動的な値を返すためには、[preg_replace_callback](https://php.net/preg_replace_callback)を使用する必要があります。 –

答えて

1

preg_replace_callback()でこれを行うことができます。置換文字列を取得する関数を呼び出し、この関数は変数をインクリメントすることができます。

$num = 0; 
$str = "some text <cs> some text </cs> some text <cs> some text </cs> some text <cs> some text </cs>"; 
$str = preg_replace_callback('/<cs>/', function($match) use (&$num) { 
    $num++; 
    return "<textarea id='codeBlock-$num'>"; 
}, $str); 
$str = str_replace("</cs>", "</textarea>", $str); 
echo $str; 

DEMO

+0

パーフェクト、ありがとう。 –

関連する問題