PHP String Replace between two html tags

自古美人都是妖i 提交于 2019-12-25 02:24:43

问题


I am trying to replace text between two tags in a html document. I want to replace any text that isn't enclosed with a < and >. I want to use str_replace to do this.

php $string = '<html><h1> some text i want to replace</h1><p>some stuff i want to replace </p>';

$text_to_echo = str_replace("Bla","Da",$String);
echo $text_to_echo;

回答1:


Try this:

    <?php

$string = '<html><h1> some text i want to replace</h1><p>
    some stuff i want to replace </p>';
$text_to_echo =  preg_replace_callback(
    "/(<([^.]+)>)([^<]+)(<\\/\\2>)/s", 
    function($matches){
        /*
         * Indexes of array:
         *    0 - full tag
         *    1 - open tag, for example <h1>
         *    2 - tag name h1
         *    3 - content
         *    4 - closing tag
         */
        // print_r($matches);
        $text = str_replace(
           array("text", "want"), 
           array('TEXT', 'need'),
                $matches[3]
        );
        return $matches[1].$text.$matches[4];
    }, 
    $string
);
echo $text_to_echo;



回答2:


str_replace() can not handle this

You will need regex or preg_replace for that



来源:https://stackoverflow.com/questions/19962053/php-string-replace-between-two-html-tags

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