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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?