正则表达式匹配Html标记和内部Html模式

时间:2015-03-25 03:41:25

标签: php regex web-scraping

我已经删除了一个网页,并且我试图从没有类或ID的td中提取数据。让我们说我有以下html:

<table> 
    <tr>
        <td>Title</td>
        <td>The Harsh Face of Mother Nature</td>
        </tr>
        .
        .
        .
</table>

我试图做preg_match

$title = preg_match("\(>Title)(.*?)(?=<\/td\>{2})\", $html);

我的模式以>Title开头,结尾是</td>的第二次出现。

我一直在与https://regex101.com/合作试图解决这个问题,但正则表达式真的很难!尤其是我试图完成的模糊东西。有什么帮助吗?谢谢!

(编辑下方:) 目标是得到一个像</td><td>The Harsh Face of Mother Nature这样的刺痛,然后再做一个preg匹配来移除第一部分,最终产品为The Harsh Face of Mother Nature

4 个答案:

答案 0 :(得分:1)

尝试其他技巧: >Title.*?(?=<td>)<td>\K.*?(?=<\/td>)

$re = "/>Title.*?(?=<td>)<td>\\K.*?(?=<\\/td>)/s";
$str = "<table> \n <tr>\n <td>Title</td>\n <td>The Harsh Face of Mother Nature</td>\n <td>The Harsh Face of Mother Nature</td>\n </tr>\n .\n .\n .\n</table>";

preg_match_all($re, $str, $matches);

Demo

答案 1 :(得分:0)

您可以在preg_match或preg_match_all

中使用以下正则表达式
>Title.*?<\/td>.*?<td>\K.*?(?=<\/td>)

DEMO

$re = "/>Title.*?<\\/td>.*?<td>\\K.*?(?=<\\/td>)/s";
$str = "<table> \n <tr>\n <td>Title</td>\n <td>The Harsh Face of Mother Nature</td>\n </tr>\n .\n .\n .\n</table>";
preg_match_all($re, $str, $matches);

答案 2 :(得分:0)

您可以尝试使用此正则表达式.*\<table\>\s*\<tr\>\s*\s*\<td\>title\<\/td>\s*\<td\>((\w*\s*\w*)*)<\/td>.*它将在第一个组中捕获<td>标记之后的<td>title</td>标记内容。

答案 3 :(得分:0)

使用js第n个子属性来获取它

$( "table tr td:nth-child(2)" )