dongmiao260399 2017-05-28 23:33
浏览 21
已采纳

PHP:用DOMText节点替换DOMElement

I want to create some customised tags for translating, for instance

<trad>SOMETHING</trad>

I've also got a file with some $GLOBALS variable, like:

$GLOBALS['SOMETHING'] = 'Some text';

$GLOBALS['SOMETHINGELSE'] = 'Some other text';

So I've been able to show my translation in this way:

$string = "<trad>SOMETHING</trad>";

$string = preg_replace('/<trad[^>]*?>([\\s\\S]*?)<\/trad>/','\\1', $string);
echo $GLOBALS[$string];

This works perfectly, but when I've got something more complex like the following code, or when I have more occurences of this tag, I'm not able to let it work:

$string = "Lorem ipsum <trad>SOMETHING</trad> <h1>Hello</h1> <trad>SOMETHINGELSE</trad>";

I ideally want to create a new variale $string, replacing the values that I found into my tags and being able to show it with a simple echo.

So I want an output like this with:

echo $string; //output: Lorem ipsum Some text <h1>Hello</h1> Some other text

Can you guys help me?

  • 写回答

1条回答 默认 最新

  • 普通网友 2017-05-29 02:21
    关注

    Regex is not a valid approach for treating HTMLstring. Here we are using DOMDocument instead of Regex to achieve desired output. The last step of strip_tags has been done to achieve desired output, there will no need in case a valid HTML string is supplied to loadHTML, in that case saveHTML($node) will do the job.

    Try this code snippet here

    <?php
    ini_set('display_errors', 1);
    
    libxml_use_internal_errors(true);
    
    $array["SOMETHING"]="some text";
    $array["SOMETHINGELSE"]="some text other";
    
    $string = "Lorem ipsum <trad>SOMETHING</trad> <h1>Hello</h1> <trad>SOMETHINGELSE</trad>";
    
    $domDocument = new DOMDocument();
    $domDocument->loadHTML($string,LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD);
    
    $results=$domDocument->getElementsByTagName("trad");
    do
    {
        foreach($results as $result)
        {
            $result->parentNode->replaceChild($domDocument->createTextNode($array[trim($result->nodeValue)]),$result);
        }
    }
    while($results->length>0);
    
    echo strip_tags($domDocument->saveHTML(),"<h1>");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何通过交互分析得出某高危患者对放疗获益更多
  • ¥15 相关性分析中,p<0.05, r=0.29,怎么评价相关性呢
  • ¥15 docker部署Mongodb后输入命令报错?
  • ¥15 将下列流程图转变成python程序代码
  • ¥15 我需要全国每个城市的最新小区名字等数据。
  • ¥15 开发一个小区生态的小程序
  • ¥15 如何解决Excel中dependent dropdown list 的问题
  • ¥15 MddBootstrapInitialize2失败
  • ¥15 LCD Flicker
  • ¥15 esp32在micropython环境下使用ssl/tls连接mqtt服务器出现以下报错Connected on 192.168.154.223发生意外错误: 5无法连接到 MQTT 代理,如何解决?