问题
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);
?>
I would like to add an id="$i++"
to every <h3>
tag.
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);
}
?>
Error: Warning: Invalid argument supplied for foreach() in...
Any ideas? M.
回答1:
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;
?>
回答2:
You first nee to get an array of all tags, you do a foreach on a string.
foreach(array("<h3>","<h3>") as $replace){
...
}
I don't tested this but this will help your way out. :-)
Regards.
来源:https://stackoverflow.com/questions/24775438/create-a-foreach-loop-on-search-and-replace