【问题标题】:Find text without any tag in a div element在 div 元素中查找没有任何标签的文本
【发布时间】:2012-07-24 14:24:30
【问题描述】:

我需要访问 div 内没有任何标签的 48.20 Lac(s) 文本,这就是我无法访问它的原因。 我需要在 PHP 文件中找到它。我试过 $html->find('div.priceDetail') 然后是 trim(strip_tags($result)) 这给了我 48.20 Lac(s) + 不必要的文本。 由于我必须构建一个通用文件,因此我不能依赖于针对特定固定情况的爆炸和内爆。

<div class="priceDetail">
    <b>Total Price :</b>
    <img alt="" src="someimage">48.20 Lac(s)
    <!-- Per Sq Ft Price -->
    <span class="pricePerSqFt">(Price per sq.ft. : Rs. 3,679)</span>
    <!-- Code for price Trends -->
    <span class="priceGrowth">4 %
        <img alt="" src="someimage"
        align="absmiddle">
        <span class="iconWhatisThis">
            <img src="someimage"
            class="whatIcon" align="absmiddle">
            <span style="" id="StoolTip" class="price_main-c"></span>
        </span>
    </span>
    <div class="tt_top-c">
        <span class="priceGrowth"></span>
    </div>
    <div class="tt_mid-c">
        <div class="tt_pointer-c"></div>
        <div>
            <span class="tt_txt-c">Per sq.ft. price for this property is
                <b>higher than the average</b>property price in this locality as per MagicBricks.com
                Price Trends.</span>
        </div>
        <span class="tt_txt-c">
            <span class="tp_txt">To know more about this
                <a href="#priceTrends" onclick="swithTab('priceTrends', tabbedDivArray);">Click
Here</a>
            </span>
        </span>
    </div>
    <div class="tt_bot-c"></div>
</div>

【问题讨论】:

    标签: php parsing html simple-html-dom


    【解决方案1】:

    使用 DOM 解析器做尽可能多的工作,然后当剩下随机加载的文本时,用这个 RegEx 提取你想要的部分:

    ([0-9]{1,5}?\.[0-9]{2} Lac\(s\))
    

    结果

    48.20 Lac(s)
    

    (将 RegEx 中的 5 更改为您希望在小数点前允许的位数)

    【讨论】:

      【解决方案2】:

      这里有一个 DomDocument 解决方案,可能比 Regex 更强大:

      $DOM = new DOMDocument;
      $DOM->loadHTML($str);
      
      //Get all the image tags
      $elem = $DOM->getElementsByTagName('img');
      //Get the first Image
      $first = $elem->item(0);
      //Get the node after the image
      $txt=  $first->nextSibling;
      //Get the text
      echo $txt->nodeValue;
      

      当然它要求文本始终位于 div 中的第一张图片之后。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-28
        • 2019-01-30
        • 1970-01-01
        • 1970-01-01
        • 2012-01-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多