2017-04-26 50 views
-2

示例代碼提前使用STR的替換功能

$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-1"秒會得到id="codeBlock-2"等等。

+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

完美,謝謝。 –