在搜索和替换上创建一个foreach循环 [英] Create a foreach-loop on search and replace
本文介绍了在搜索和替换上创建一个foreach循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
现在我的WordPress网站有一个脚本,它找到了一个< h3>
-tag并添加了一个 id
to it
I currently have a script for my WordPress site that finds a <h3>
-tag and adds an id
to it
<?php
$phrase = get_the_content();
$phrase = apply_filters('the_content', $phrase);
$replace = '<h3 id="thetag">';
echo str_replace('<h3>', $replace, $phrase);
?>
我想添加一个 id =$ i ++
标记
我想过这个,但是这给了我一个foreach错误:
I thought about this but that gives me an foreach error:
<?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);
}
?>
错误:警告:提供的foreach
有什么想法?
M。
Any ideas? M.
推荐答案
在str_replace函数中,第三个参数是一个输出变量,用于检查执行了多少次替换。使用preg_replace函数:
In str_replace function third parameter is an output variable to check how many replacements were performed. Use preg_replace function:
<?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;
?>
这篇关于在搜索和替换上创建一个foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文