【问题标题】:Str Replace value in XML tagStr 替换 XML 标记中的值
【发布时间】:2023-03-28 16:46:01
【问题描述】:

我想用 PHP 的 str_replace 函数替换这个标签中的值:

<address2>Replace this value</address2>

最好的方法是什么?

【问题讨论】:

标签: php


【解决方案1】:

试试这个:

$nodeAdresseValue = str_replace("%value%", "your value", "<address2>%value%</address2>");

【讨论】:

    【解决方案2】:

    不要在 XML 上使用字符串函数,而是使用 DOMDocument,它会帮助您更轻松地解析 XML,这是一个示例代码 DEMO

    <?php
    
    $string = "<address2>Replace this value</address2>";
    $domDocument = new DOMDocument();
    $domDocument->loadXML($string);
    $address2Elements = $domDocument->getElementsByTagName('address2');
    foreach ($address2Elements as $address2) {
            $address2->nodeValue = "Value Replaced";
    
    }
    
    var_dump($domDocument->saveXML());
    

    输出:

    string(58) "<?xml version="1.0"?>
    <address2>Value Replaced</address2>
    "
    

    【讨论】:

      【解决方案3】:
      $search  = "/[^<address2>](.*)[^<\/address2>]/";
      $replace = "replace with me";
      $string  = "<address2>Replace this value </address2>";
      echo preg_replace($search,$replace,$string);
      

      不管文本如何,它都可以工作,即使你不知道标签内的值也可以工作

      【讨论】:

        猜你喜欢
        • 2013-11-19
        • 2011-01-07
        • 2013-05-04
        • 2019-01-09
        • 1970-01-01
        • 2019-12-28
        • 1970-01-01
        • 1970-01-01
        • 2020-12-26
        相关资源
        最近更新 更多