Php 在搜索和替换时创建foreach循环
我目前有一个WordPress网站的脚本,它可以找到一个Php 在搜索和替换时创建foreach循环,php,wordpress,loops,foreach,add,Php,Wordpress,Loops,Foreach,Add,我目前有一个WordPress网站的脚本,它可以找到一个-标记,并向其中添加一个id <?php $phrase = get_the_content(); $phrase = apply_filters('the_content', $phrase); $replace = '<h3 id="thetag">'; echo str_replace('<h3>', $replace, $phrase); ?> 错误:警告:为
-标记,并向其中添加一个id
<?php
$phrase = get_the_content();
$phrase = apply_filters('the_content', $phrase);
$replace = '<h3 id="thetag">';
echo str_replace('<h3>', $replace, $phrase);
?>
错误:警告:为…中的foreach()提供的参数无效。
有什么想法吗?
M.首先需要获取所有标记的数组,然后对字符串执行foreach
foreach(array("<h3>","<h3>") as $replace){
...
}
foreach(数组(“,”)作为$replace){
...
}
我没有对此进行测试,但这将帮助您走出困境。:-)
注意。在str_replace函数中,第三个参数是一个输出变量,用于检查执行了多少次替换。使用preg_替换功能:
<?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;
?>
$i=o;字符串上的foreach循环不会发生。您应该首先找到一种对内容进行爬网的方法。然后对该方法的响应使用foreach웃 Thnx。我会先尝试这样做是的,但我首先需要一个循环来做,因为我永远不知道会有多少个
行:echo preg\u replace($tag,$replace,$phrase,1);我们必须用新值替换$phrase字符串。请使用:$phrase=preg_replace($tag,$replace,$phrase,1);回音$短语;美好的但是,这仅适用于第一个
。我想是出了问题,因为有一些丢失的>和<标签。“这是一个H3标题”。FireBug告诉我:<>这是一个H3标题这是另一个相同的结果。你能解释一下“1”在preg_replace()中的作用吗;?preg_replace中的第三个参数定义将有多少个替换为新值。Thnx。我试图添加错误,但没有错误:-(顺便说一句,它会将页面内容重复6次…?每次内容重新加载$I++时,都会添加1
<?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;
?>