多个通配符 preg_match_all PHP

5

我想从html中提取一个数字,介于<td>...</td>之间。我尝试过以下代码:

$views = "/<td id=\"adv-result-views-(?:.*)\" class=\"spec\">(.*?)<\/td>/";

在 -views- 后面是一个随机数字。如何正确编写代码以忽略搜索中的随机数字?


你能否提供一下你想匹配的HTML示例? - Pedro Lobito
<td id="adv-result-views-190147977" class="spec"> 4 </td> 我想用 preg_match_all 获取数字 4。 - user3625376
adv-result-views-\d+ - bansi
1
@PedroLobito,不要再宣传你的答案了。当你发布一次后,OP会收到通知。 - Shankar Narayana Damodaran
2个回答

1
使用DOM将是正确的方法。
按照以下步骤进行...
<?php
$htm = '<td id="adv-result-views-190147977" class="spec"> 4 </td>';
$dom = new DOMDocument;
$dom->loadHTML($htm);
echo $content = $dom->getElementsByTagName('td')->item(0)->nodeValue; //4

我想提取的不是数字,而是你的示例中的“Sometext”。由于该类在多个<td>中使用且ID是随机的,因此无法使用DOM。 - user3625376
我认为你没有完全理解这个问题。 - Pedro Lobito
3
@ShankarDamodaran 在使用 DOM 的方法上是正确的。 - hank

1
$html = '<td id="adv-result-views-190147977" class="spec"> 4 </td>';

// get the value of element
echo trim( strip_tags( $html ) );

// get the number in id attribute, replace string with group capture $1
echo preg_replace( '/^.*?id="[\pLl-]+(\d+).*$/s', '$1', $html );   
/*
    ^.*?id="            Any character from the beginning of string, not gready
        id="            Find 'id="'
            [\pLl-]+    Lower case letter and '-' ( 1 or more times )
            (\d+)       Group and capture to \1 -> digits (0-9) (1 or more times) -> end of \1                      
    .*$                 Any character, gready, until end of the string
*/

// get html withut the number in id attribute
echo preg_replace( '/(^.*?id="[\pLl-]+)(\d+)(.*$)/s', '$1$3', $html );

由于问题标记为正则表达式,这是一个正则表达式示例,但DOM是解析HTML的首选方式(特别是在SO社区中)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接