使用RegEx在HTML标记之间查找内容

时间:2016-03-03 07:49:03

标签: javascript php jquery html regex

我想提取具有属性名称SELECT RowNumber(city) AS RowID, * FROM City 的网页的内容。假设我的页面有不同的HTML标记,其属性名为itemprop,所以我希望在这些标记之间插入文本,

标题:

itemprop

来自td标签的表数据:

<h1 itemprop="name" class="h2">Whirlpool Direct Drive Washer Motor Coupling</h1>

此处<td itemprop="productID">AP3963893</td> 属性很常见。因此,我需要使用regexp在itempropWhirlpool Direct Drive Washer Motor Coupling等标记之间使用数据。

以下是我的代码(目前无效)

AP3963893

我的代码:

preg_match_all(
    '/<div class=\"pdct\-inf\">(.*?)<\/div>/s',
    $producturl,
    $posts    
);

2 个答案:

答案 0 :(得分:1)

首先,GameObject.Instantiate。其次,您可以使用jQuery非常简单地通过使用属性选择器实现此目的:

var nameItemprop = $('[itemprop="name"]').text(); // = 'Whirlpool Direct Drive Washer Motor Coupling'
var productIdItemprop = $('[itemprop="productID"]').text(); // = 'AP3963893'

但请注意,创建自己的非标准属性是无效的HTML。理想情况下,您应该使用data-*属性来包含与这些元素关联的数据:

<h1 data-itemprop="name" class="h2">Whirlpool Direct Drive Washer Motor Coupling</h1>
<td data-itemprop="productID">AP3963893</td>
var nameItemprop = $('[data-itemprop="name"]').text();
var productIdItemprop = $('[data-itemprop="productID"]').text();

最后,如果有多个元素具有相同的itemprop属性,那么您需要循环遍历它们以从每个单独的元素中获取值。

答案 1 :(得分:0)

如前所述,您不应该使用RegExp来解析HTML,但如果您坚持这样做,这里应该有一个模式:

$producturl = '<h1 itemprop="name" class="h2">Whirlpool Direct Drive Washer Motor Coupling</h1>';

if (preg_match_all(
   '/<.*itemprop=\".*\".*>(.*?)<\/.*>/s',
   $producturl,
   $posts    
)) {
    print_r($posts);
}

这会创建以下输出:

Array
(
    [0] => Array
        (
            [0] => <h1 itemprop="name" class="h2">Whirlpool Direct Drive Washer Motor Coupling</h1>
        )
    [1] => Array
        (
            [0] => Whirlpool Direct Drive Washer Motor Coupling
        )
)