Create a foreach-loop on search and replace

房东的猫 提交于 2019-12-13 05:05:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!