PHP 预匹配 html 文件。正则表达式
PHP Preg match on html file. Regex
我想把法语单词放在一个数组中。
<?php
$contents = file_get_contents("http://quizlet.com/9117/envol-7-unite-1-presentation-flash-cards/");
$pattern = '/<span class="TermText qWord lang-fr">(.*?)</s';
preg_match($pattern,$contents, $matches);
print_r($matches);
?>
这段代码的结果是一个空数组。
源页面用单引号将 class 值括起来。您还需要使用 preg_match_all()
函数来获取所有结果。
<?php
$contents = file_get_contents("http://quizlet.com/9117/envol-7-unite-1-presentation-flash-cards/");
$pattern = "/<span class='TermText qWord lang-fr'>(.*?)\</s";
preg_match_all($pattern,$contents, $matches);
print_r($matches);
?>
如果你想获取 <span>
标签的所有内部文本 class
属性值中有 lang-fr
,你可以使用以下基于 DOMDocument/DOMXPath 的解决方案:
$contents = file_get_contents("http://quizlet.com/9117/envol-7-unite-1-presentation-flash-cards/");
$dom = new DOMDocument;
@$dom->loadHTML($contents, LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD);
$xp = new DOMXPath($dom);
$spans = $xp->query('//span[contains(@class,"lang-fr")]');
$arr = array();
foreach ($spans as $span) {
array_push($arr, $span->nodeValue);
}
print_r($arr);
这里的 xpath 是 '//span[contains(@class,"lang-fr")]'
。您可以更严格地只获取所有 class 属性值等于 "TermText qWord lang-fr" 的 span 标签:'//span[@class="lang-fr"]'
.
此解决方案使您免于在 HTML 中匹配这种或那种类型的定界属性值的问题。以及与正则表达式 HTML 解析相关的许多其他问题。
我想把法语单词放在一个数组中。
<?php
$contents = file_get_contents("http://quizlet.com/9117/envol-7-unite-1-presentation-flash-cards/");
$pattern = '/<span class="TermText qWord lang-fr">(.*?)</s';
preg_match($pattern,$contents, $matches);
print_r($matches);
?>
这段代码的结果是一个空数组。
源页面用单引号将 class 值括起来。您还需要使用 preg_match_all()
函数来获取所有结果。
<?php
$contents = file_get_contents("http://quizlet.com/9117/envol-7-unite-1-presentation-flash-cards/");
$pattern = "/<span class='TermText qWord lang-fr'>(.*?)\</s";
preg_match_all($pattern,$contents, $matches);
print_r($matches);
?>
如果你想获取 <span>
标签的所有内部文本 class
属性值中有 lang-fr
,你可以使用以下基于 DOMDocument/DOMXPath 的解决方案:
$contents = file_get_contents("http://quizlet.com/9117/envol-7-unite-1-presentation-flash-cards/");
$dom = new DOMDocument;
@$dom->loadHTML($contents, LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD);
$xp = new DOMXPath($dom);
$spans = $xp->query('//span[contains(@class,"lang-fr")]');
$arr = array();
foreach ($spans as $span) {
array_push($arr, $span->nodeValue);
}
print_r($arr);
这里的 xpath 是 '//span[contains(@class,"lang-fr")]'
。您可以更严格地只获取所有 class 属性值等于 "TermText qWord lang-fr" 的 span 标签:'//span[@class="lang-fr"]'
.
此解决方案使您免于在 HTML 中匹配这种或那种类型的定界属性值的问题。以及与正则表达式 HTML 解析相关的许多其他问题。