【问题标题】:PHP String Replace between two html tags两个html标签之间的PHP字符串替换
【发布时间】:2013-11-26 13:01:18
【问题描述】:

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

【问题讨论】:

标签: php html string str-replace


【解决方案1】:

试试这个:

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

【讨论】:

  • 谢谢,有没有办法逐字逐句。例如用“hello”替换“text”,用“cake”替换“want”
  • 谢谢,太好了。
  • 嗨。是否有一种简单的方法来实现 MySQL,因为我想从数据库中获取数组,而不是手动插入它们。
  • 您好,如果您打算进一步使用这些数据,这些数据是插入到 mysql 中的,而不是替换,那么值得这样做一次。
【解决方案2】:

str_replace()不能处理这个

你需要regexpreg_replace 来做这个

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    • 2014-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多