【问题标题】:replace div with its content用它的内容替换 div
【发布时间】:2013-02-17 06:59:21
【问题描述】:

我正在尝试过滤 html 代码

代码包含一个带有行类的 div

我想用那里的内容替换这些 div

例如:

<div class="row anotherClass">some html code 1</div>
<div class="row anotherClass">some html code 2</div>
<div class="row anotherClass">some html code 3</div>

输出应该是这样的

some html code 1
some html code 2
some html code 3

我写了以下表达式(我不太擅长正则表达式)但输出 html 仍然没有很好地过滤有时 div 开头仍然存在 有时 div 结尾仍然存在

$output = preg_replace_callback('/<div class="row (.*?)">(.*)<\/div>/s', function ($matches) {
            return $matches[2];

        }, $output);

【问题讨论】:

    标签: php regex html-parsing


    【解决方案1】:

    你是这个意思吗?

    <?php
    
    $html = '<div class="row anotherClass">some html code 1</div>
    <div class="row anotherClass">some html code 2</div>
    <div class="row anotherClass">some html code 3</div>';
    
    $reg = '(<div class="row anotherClass">(.*?)</div>)';
    preg_match_all($reg, $html, $divs);
    
    $div_contents = $divs[1];
    $divs = $divs[0];
    
    $replaced_html = $html;
    
    for ($i=0; $i < count($divs); $i++) {
        $replaced_html = str_replace($divs[$i], $div_contents[$i], $replaced_html);
    }
    
    echo $replaced_html;
    
    ?>
    

    【讨论】:

    • 感谢重播该功能在经过一些修改后正常工作,但输出 html 已损坏输入进入 errorMessage div 这是一个示例
    • $html = '

      :

      '; $reg = '/
      (.*?)./sm'; preg_match_all($reg, $html, $divs); $div_contents = $divs[2]; $divs = $divs[0]; print_r($div_contents); $replaced_html = $html; for ($i=0; $i
    • 内部 div 有问题
    • 试试 $reg = '/
      (.*?)./sm';替换 $reg = '/(
      (.*?).)/sm';
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签