duanduji2986 2012-08-25 05:23
浏览 37
已采纳

添加  PHP中的非标记HTML文本

I have this kind of HTML document.

<span class="class1">text1</span>
<a href="">link1</a>
<font color=""><b>text2</b></font>
<a href="">link2</a>
text3
<span class="class2">text4</span>

And I'd like to surround text1, text2 and text3 by &nbsp;s. What would be the best way? DomDocument cannot catch strings that are not tagged. For text1 and text2, getElementByTagName('tagname')->item(0) can be used but for text 3, I'm not sure what to do.

Any ideas?

[Edit]

As Musa suggests, I tried using nextSibling.

<?php
$html = <<<STR
    <span class="class1">text1</span>
    <a href="">link1</a>
    <font color=""><b>text2</b></font>
    <a href="">link2</a>
    text3
    <span class="class2">text4</span>
STR;

$doc = new DOMDocument;
$doc->loadHTML($html);
foreach ($doc->getElementsByTagName('a') as $nodeA) {
    $nodeA->nextSibling->nodeValue = '&nbsp;' . $nodeA->nextSibling->nodeValue . '&nbsp;';
}
echo $doc->saveHtml();
?>

However, &nbsp;gets escaped and converted to &amp;nbsp;

  • 写回答

3条回答 默认 最新

  • doumeng1089 2012-08-25 21:19
    关注

    Since the setting the value seems to set it as text and not html you could use the non-breaking space character instead of the html entity.

    <?php
    $html = <<<STR
        <span class="class1">text1</span>
        <a href="">link1</a>
        <font color=""><b>text2</b></font>
        <a href="">link2</a>
        text3
        <span class="class2">text4</span>
    STR;
    $nbsp = "\xc2\xa0";
    $doc = new DOMDocument;
    $doc->loadHTML('<div>' . $html . '</div>');
    
    foreach( $doc->getElementsByTagName('div')->item(0)->childNodes as $node ) {
        if ($node->nodeType == 3) {     // nodeType:3 TEXT_NODE
            $node->nodeValue = $nbsp . $node->nodeValue . $nbsp;
        }
    }
    echo $doc->saveHtml();
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算