多个通配符preg_match_all php

时间:2014-05-11 11:40:50

标签: php html regex preg-match-all

我想从<td>...</td>之间的html中提取一个数字。我试着遵循以下代码:

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

after -views-是一个随机数。在搜索中忽略随机数的正确代码是什么?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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社区)。