我目前在我的WordPress网站上有一个脚本,可以找到<h3>
- 代码,并为其添加id
<?php
$phrase = get_the_content();
$phrase = apply_filters('the_content', $phrase);
$replace = '<h3 id="thetag">';
echo str_replace('<h3>', $replace, $phrase);
?>
我想在每个id="$i++"
代码中添加<h3>
。
我想到了这个,但这给了我一个foreach错误:
<?php
$phrase = get_the_content();
$phrase = apply_filters('the_content', $phrase);
$tag='<h3>';
$i=0;
foreach ($tag as $replace){
$replace = '<h3 id="'.$i++.'">';
echo str_replace($tag, $replace, $phrase);
}
?>
错误:Warning: Invalid argument supplied for foreach() in...
有什么想法吗? 微米。
答案 0 :(得分:1)
在str_replace函数中,第三个参数是一个输出变量,用于检查执行的替换次数。使用preg_replace函数:
<?php
$phrase = get_the_content();
$phrase = apply_filters('the_content', $phrase);
$tag='<h3>';
$i=0;
$c = substr_count($phrase, $tag);
for($i=0; $i<$c; $i++){
$replace = '<h3 id="'.$i.'">';
$phrase = preg_replace('/'.$tag.'/', $replace, $phrase, 1);
}
echo $phrase;
?>
答案 1 :(得分:0)
首先需要获取所有标签的数组,然后对字符串进行操作。
foreach(array("<h3>","<h3>") as $replace){
...
}
我没有对此进行测试,但这将有助于您解决问题。 : - )
问候。