【问题标题】:How to get content from Div which have other HTML tags using Regexp如何使用正则表达式从具有其他 HTML 标记的 Div 获取内容
【发布时间】:2016-03-04 06:59:43
【问题描述】:

我的 div 包含其他 html tagstext

我只想从此 div 或所有 html tags 中提取文本

<div class="rpr-help m-chm">
                <div class="header">
                    <h2 class="h6">Repair Help</h2>
                </div><!-- /end .header -->
                <div class="inner m-bsc">
                    <ul>


                        <li><a href="#videol">Repair Video</a></li>

                        <li><a href="#qa1">Repair Q&amp;A</a></li>
                    </ul>
                </div>

                    <div>
                    <br>
                    <span class="h4">Cross Reference Information</span><br>
                    <p>Part Number 285753A (AP3963893) replaces  1195967, 280152, 285140, 285743, 285753, 3352470, 3363664, 3364002, 3364003, 62672, 62693, 661560, 80008, 8559748, AH1485646, EA1485646, PS1485646.
                    <br>
                    </p>
                    </div>

            </div>

这是我的Regexp

preg_match_all("/<div class=\"rpr-help m-chm\">(.*)<\/.*>/s", $urlcontent, $description);

每当我将这个完整的 div 分配给 $urlcontent 变量时,它都可以正常工作。

但是当我从像$urlcontent = "www.test.com/test.html";这样的真实网址获取数据时 它返回完整的网页脚本。

如何获取 &lt;div class="rpr-help m-chm"&gt; 的内部内容?

我的正则表达式是否需要更正?

任何帮助将不胜感激。谢谢

【问题讨论】:

    标签: php html regex


    【解决方案1】:

    无法通过正则表达式解析 HTML/XHTML。 Source

    您无法使用正则表达式解析 [X]HTML。因为 HTML 无法解析 正则表达式。正则表达式不是一个可以用来正确解析 HTML 的工具

    根据您使用的语言,请考虑使用第三方库进行 HTML 解析。

    【讨论】:

    【解决方案2】:
    use this function
    
        function GetclassContent($tagStart,$tagEnd,$content)
        {
            $first_step = explode( $tagStart,$content );
            $second_step = explode($tagEnd,$first_step[1] );
            return $second_step[0];
        }
    
    Steps to Use Above function 
    $website="www.test.com/test.html";
    $content=file_get_contents($website);
    $tagStart ='<div  class="rpr-help m-chm">';
    $tagEnd   = "</div >";
    $RequiredContent = GetclassContent($tagStart,$tagEnd,$content);
    

    【讨论】:

    • 它还包含其他的
      。如果它采用第一个结束标签怎么办,那么它将跳过其他包含
  • @RahulDambare 现在您可以自定义“GetclassContent”函数以获得所需或想要的结果。
  • 猜你喜欢
    • 2013-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多