PHP字符串替换两个html标记

时间:2013-11-13 18:54:48

标签: php html string str-replace

我正在尝试替换html文档中两个标记之间的文本。我想替换任何未附加<的文本。和>。 我想用str_replace来做这件事。

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;

2 个答案:

答案 0 :(得分:0)

str_replace()无法处理此

您需要regexpreg_replace

答案 1 :(得分:0)

试试这个:

    <?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;