正则表达式查找并修改<table> </table>

时间:2014-04-15 08:04:20

标签: php regex html-table

我的代码看起来像下面那样,将从CMS生成。 用户可以生成一个表,但我必须在其周围放置一个<div>

<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et 
dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo 
dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem</p>

<table>
<thead>
    <tr><td></td></tr>
    ...
</tbody>
</table>

<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et 
dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo 
dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem</p> 
<table>
<thead>
    <tr><td></td></tr>
    ...
</tbody>
</table>
...

我的目标是现在给每个<table>一个<div class="table">

我用regex试了一下并得到了这个结果:

function smarty_modifier_table($string) {
    preg_match_all('/<table.*?>(.*?)<\/table>/si', $string, $matches);
    echo "<pre>";
    var_dump($matches);
}
/* result
array(2) {
    [0]=> string(949) "<table>...</table>"
    [1]=> string(934) "<thead>...</tbody>"
}
array(2) {
    [0]=> string(949) "<table>...</table>"
    [1]=> string(934) "<thead>...</tbody>"
}
*/

首先,我不明白为什么出现第二个array [1]=> string(934) "<thead>...</tbody>" 第二,如何将修改过的数组放回到正确位置的字符串中。

3 个答案:

答案 0 :(得分:0)

$buffer = preg_replace('%<table>(.*?)</table>%sim', '<table><div class="table">$1</div></table>', $buffer);

答案 1 :(得分:0)

如果您的html非常简单,那么以下内容可能会有效:

print preg_replace('~<table.+?</table>~si', "<div class='table'>$0</div>", $html);

但是,如果您可以使用嵌套表:

<table>
    <tr><td> <table>INNER!</table> </td></tr>
</table>

这个表达式会失败 - 这就是为什么不推荐使用正则表达式解析html的原因。要处理复杂的html,最好使用解析器库,例如XML DOM:

$doc = new DOMDocument();
$doc->loadHTML($html);
$body = $doc->getElementsByTagName('body')->item(0);
foreach($body->childNodes as $s) {
    if($s->nodeType == XML_ELEMENT_NODE && $s->tagName == 'table') {
        $div = $doc->createElement("div");
        $div->setAttribute("class", "table");
        $body->replaceChild($div, $s);
        $div->appendChild($s);
    }
}

这个正确处理嵌套表。

答案 2 :(得分:0)

感谢大家快速而完美的帮助! 所以它对我有用。

$ result = preg_replace(&#39; ~~ si&#39;,&#34; $ 0&#34;,$ string);

返回$ result;

问候

的Torsten