0

我正在尝试替换 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;
4

2 回答 2

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;
于 2013-11-13T18:59:20.363 回答
0

str_replace()不能处理这个

您将需要regexpreg_replace为此

于 2013-11-13T18:57:24.903 回答