php preg_match表和包装div

时间:2015-07-20 23:47:51

标签: php regex twitter-bootstrap preg-match

我有CMS驱动的内容,在保存准备内容时,作为其中的一部分,我想清理作者创建的表格。

我们在前端使用BootStrap,因此希望能够先抓住所有表格。 检查父元素,如果它不是<div class="table-resposnsive">,则将其包装在其中。

我有:

// $content = $_POST['content']; 
// Set some TEST content
$content = "<h1>My Content</h1>
    <p>This is some content</p>
    <table border=\"1\">
        <tr>
            <td>cell</td>
            <td>cell</td>
            <td>cell</td>
        </tr>
        <tr>
            <td>cell</td>
            <td>cell</td>
            <td>cell</td>
        </tr>
    </table>
    <div align=\"center\">see the above content</div>
    <p>Thanks!</p>\n\n";

// Make our example content longer with more variations... 
$content = $content . 
    str_replace('<table border="1">', '<table border="0" class="my-table">', $content) . 
    str_replace('<table border="1">', '<table border="0" cellpadding="0" cellspacing="3">', $content);

$output  = $content;

// Parse for table tags
preg_match_all("/<table(.*?)>/", $content, $tables);

// If we have table tags.. 
if(count($tables[1]) > 0) {

    // loop over and get teh infor we want to build the new table tag. 
    foreach($tables[0] as $key => $match) {
        $add_class = array();
        $tag = ' '. $tables[1][$key] .' ';
        $add_class[] = 'table';
        // check if we have got Borders....
        // If we do. add the bootstrap table-border calss. 
        if(strpos($tag, 'border="0"') === FALSE) {
            $add_class[] = 'table-bordered';
        }
        // prepend any existing/custom classes. 
        if(strpos($tag, 'class="') > 0) {
            preg_match("/class=\"(.*?)\"/", $tag, $classes);
            if($classes[1]) {
                $add_class = array_merge($add_class, explode(' ', $classes[1]));
            }
        }
        // add classes. 
        $add_class = array_unique($add_class);

        // Now - replace the original <table> tag with the new BS tag. 
        // adding any class attrs
        // wrap in the responsive DIV. - THIS part - needs to be only added if its not already wrapped... 
        // this would happen if we have already edited the page before right ... 
        $output = str_replace($match, '<div class="table-responsive">'."\n".'<table class="'. implode(' ', $add_class) .'">', $output);

    }

    // replace all closing </table> tags with the closing responsive tag too... 
    $output = str_replace('</table>', '</table>'."\n".'</div>', $output);

} 

echo highlight_string($content, TRUE);
echo '<hr>';
echo highlight_string($output, TRUE);

1 个答案:

答案 0 :(得分:1)

您可以使用Simple HTML dom解析器来选择div https://github.com/sunra/php-simple-html-dom-parser

$html = new simple_html_dom();
$html->file_get_html(__filepath__);
# get an element representing the second paragraph
$element = $html->find("#youdiv");`
祝你好运