可能重复:
Best methods to parse HTML with PHPPHP,我该如何使用preg_match?
我有数据里面包含了很多次:
<td width="183">//I want to find what's here</td>
这td
是在这个网站的每个项目,我该怎么办获取每个td
的内容?
可能重复:
Best methods to parse HTML with PHPPHP,我该如何使用preg_match?
我有数据里面包含了很多次:
<td width="183">//I want to find what's here</td>
这td
是在这个网站的每个项目,我该怎么办获取每个td
的内容?
通常你最好关闭使用DOM文档的所有HTML/XML解析:
$doc = new DomDocument();
$doc->loadHTML('<html>...</html>');
foreach($dom->getElementsByTagName('td') as $node)
{
echo $node->nodeValue;
}
为了得到一个TD与宽度= “183”,那么你可以使用DomXPath
$xpath = new DOMXpath($dom);
$elements = $xpath->query("*/td[@width='183']");
foreach($elements as $node)
{
echo $node->nodeValue;
}
但也有很多'td'我想'183''宽度'正好 – user850019
@user看到更新 – cwallenpoole
你不能给我一种方式使用'preg_match',因为有另一件事,我会使用'preg_match',所以如果你给我一个代码,对我来说通过这个来学习会更好。 – user850019
好,最好不要与preg_match ...更好地与:
php > $xml = new SimpleXmlElement('<root><td width="183">A</td><td width="182">B</td><td width="181">C</td></root>');
php > foreach($xml->xpath('//td[@width=183]') as $td) echo (string)$td,"\n";
A
或类似。
如果你绝对要...:
php > preg_match_all('/<td width="183">(.*?)<\\/td>/', '<root><td width="183">A</td><td width="182">B</td><td width="181">C</td></root>', $matches);
php > var_dump($matches);
array(2) {
[0]=>
array(1) {
[0]=>
string(22) "<td width="183">A</td>"
}
[1]=>
array(1) {
[0]=>
string(1) "A"
}
}
反正......我告诉你,这正则表达式的方法是容易破碎,不推荐。
编辑:我解决了从开始就不清楚的“只有183” - 部分。
与带有loadHTML方法的DOM不同,当它无效时,SimpleXML将失败XHTML – Gordon
使用preg_match_all(),并检查该示例中出:
<?php
// The \\2 is an example of backreferencing. This tells pcre that
// it must match the second set of parentheses in the regular expression
// itself, which would be the ([\w]+) in this case. The extra backslash is
// required because the string is in double quotes.
$html = "<b>bold text</b><a href=howdy.html>click me</a>";
preg_match_all("/(<([\w]+)[^>]*>)(.*?)(<\/\\2>)/", $html, $matches, PREG_SET_ORDER);
foreach ($matches as $val) {
echo "matched: " . $val[0] . "\n";
echo "part 1: " . $val[1] . "\n";
echo "part 2: " . $val[2] . "\n";
echo "part 3: " . $val[3] . "\n";
echo "part 4: " . $val[4] . "\n\n";
}
?>
上面的示例将输出:
匹配:粗体文本
第1部分:<b>
第2部分:乙
第3部分:粗体文本
第4部分:</b>
匹配:点击我
第1部分:<a href=howdy.html>
第2部分:一个
第3部分:按我
第4部分:</a>
正如你可以,你可以在$回声$ VAL [3]来获得html标签内部是什么。我从这个链接中得到了例子。
相关:最好的方法来解析与PHP HTML(http://stackoverflow.com/questions/3577641/best-methods-to-parse-html-with-php) –