php str_replace static to a dynamic id


php str_replace static to a dynamic id

我有以下代码:

<strong>this is test1 </strong>
<strong>this is test2 </strong>
<strong>this is test3 </strong>
<strong>this is test4 </strong>

我需要把它改成:

<div id="test1"><strong>this is test1 </strong></div>
<div id="test2"><strong>this is test2 </strong></div>
<div id="test3"><strong>this is test3 </strong></div>

用str_replace之类的。。。有什么想法吗?由于文本来自CMS。当菜单项被点击时,我需要有这个文本的id才能移动到小节。

尝试:

for ($i = 1; $i <= 4; $i++) {
$test$i = str_replace('<strong>','<div id="test'.$i.'"><strong>',
    '<strong>this is test'.$i.'</strong>');
$test$i = str_replace('</strong>','</strong></div>',
    $test$i);
}

现在您将拥有$test1、$test2、$test3和$test4。

编辑:请注意,PHP是服务器端的,您必须重新加载页面才能执行PHP代码。

编辑:新代码:

$text = '<strong>this is a test</strong><strong>this is a test</strong>';
function str_replacef($from, $to, $subject)
{
    $from = '/'.preg_quote($from, '/').'/';
    return preg_replace($from, $to, $subject, 1);
}
for ($i = 1; $i <= 2; $i++) {
$text = str_replacef('<strong>','<div id="'.$i.'"><strong2>',$text);
$text = str_replacef('</strong>','</strong2></div>',$text);
}
$text = str_replace('<strong2>','<strong>',$text);
$text = str_replace('</strong2>','</strong>',$text);
echo $text;

您也可以使用preg_replace。

我在工作时用手机打字,但像这样的东西和Björns的for循环答案就可以了。

preg_replace("/(<strong>.*<'/strong>)/", "<div id=test" . $i . ">$1</div>"