可能的重复:
使用 PHP 解析 HTML 的最佳方法
我有一些将表行与 preg 匹配时遇到问题。这是我的表达式:
<TR[a-z\=\"a-z0-9 ]*>([\{\}\(\)\^\=\$\&\.\_\%\#\!\@\=\<\>\:\;\,\~\`\'\*\?\/\+\|\[\]\|\-a-zA-Z0-9À-ÿ\n\r ]*)<\/TR>
如您所见,它尝试匹配 TR 标记之间的所有内容(包括所有符号)。该部分效果很好,但是在处理多个表行时,它通常将多个表行作为一个匹配,而不是比每个表行的匹配:
<TR>
<TD>test</TD>
</TR>
<TR>
<TD>test2</TD>
</TR>
产生:
Array
(
[0] => <TD>test</TD>
<TD>test2</TD>
)
而不是我想要的:
Array
(
[0] => <TD>test</TD>
[1] => <TD>test2</TD>
)
我意识到这样做的原因是因为它与符号匹配,并且搜索自然会获取其余行,直到找到最后一行。
所以基本上,我想知道是否有人可以帮助我添加到表达式中,以便它将排除 TR 标记之间带有“TR”的任何内容,以防止它匹配多行。
Possible Duplicate:
Best methods to parse HTML with PHP
I'm having a bit of trouble matching table rows with preg. Here is my expression:
<TR[a-z\=\"a-z0-9 ]*>([\{\}\(\)\^\=\$\&\.\_\%\#\!\@\=\<\>\:\;\,\~\`\'\*\?\/\+\|\[\]\|\-a-zA-Z0-9À-ÿ\n\r ]*)<\/TR>
As you can see, it tries to mach everything in-between TR tags (including all symbols.) That part works great, however when dealing with multiple table rows, it often takes multiple table rows as ONE match, rather than a match for each table row:
<TR>
<TD>test</TD>
</TR>
<TR>
<TD>test2</TD>
</TR>
yields:
Array
(
[0] => <TD>test</TD>
<TD>test2</TD>
)
rather than what I want it to:
Array
(
[0] => <TD>test</TD>
[1] => <TD>test2</TD>
)
I realize that the reason for this is because it's match the symbols, and the search naturally takes the rest of the rows until it hits the last one.
So basically, I'm wondering if someone can help me add to the expression so that it will exclude anything with "TR" in between the TR tags, as to prevent it from matching multiple rows.
发布评论
评论(2)
在正则表达式中使用惰性匹配:
但正如其他人提到的,如果可以的话,使用适当的解析器会更健壮。
Use lazy matching in your regex:
<tr.*?</tr>
But as others have mentioned, it's more robust to use a proper parser if you can.
尝试使用全局搜索:
preg_match_all("/([^<]+)/", $html, $matches);
Try using global search:
preg_match_all("/<td>([^<]+)/", $html, $matches);