duanpin9531 2012-11-13 22:29
浏览 28

用php regex替换标签的html

I have a situation in which I think I may have to use regex to alter html tag content or src based on the class attribute.

To document I will be parsing will be either nicely formed html, partial html or php files.

EG I would need to change/fill these tags with inner content: fileX.php

<?php
echo <<<_END
<div class="identifyingClass1"></div>
<div class="identifyingClass2"><span>holding content</span></div>
<img src='http://source.com/to/change' class='identifyingClass3' alt='descrip'/>
_END;

Resulting fileX.php

<?php
echo <<<_END
<div class="identifyingClass1">New content jsd soisvkbsdv</div>
<div class="identifyingClass2">More new content</div>
<img src='new/source.tiff' class='identifyingClass3' alt='descrip'/>
_END;

The html could be complete, could be separated by php, be as is, be inside a hereDOC...

Is the best way to achieve this to just use regex or has anyone seen or used a class for this kind of thing?

  • 写回答

2条回答 默认 最新

  • douba9425 2012-11-13 22:37
    关注

    Regex is evil for such case. Better you work on the generated html. Here's how you do it.

    Enable output buffering. On the ob_start function add your own callback. Process the generated html with DOMDocument inside the handler. Something like this,

    function my_handler($contents){
         $doc = DOMDocument::loadHTML ($contents);
         // change your document here and return it later
         return $doc->saveHTML();
    }
    ob_start('my_handler');
    
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥20 求用stm32f103c6t6在lcd1206上显示Door is open和password:
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法