Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
html文件上的PHP Preg匹配。正则表达式_Php_Regex_Preg Match - Fatal编程技术网

html文件上的PHP Preg匹配。正则表达式

html文件上的PHP Preg匹配。正则表达式,php,regex,preg-match,Php,Regex,Preg Match,我想把法语单词排成一个数组 <?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($m

我想把法语单词排成一个数组

<?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); 

?>


此代码的结果是一个空数组。

源页面将类值括在单引号中。您还需要使用
preg\u match\u 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); 

?>

如果您想在
属性值中获取具有
lang fr
标记的所有内部文本,可以使用以下基于DOMDocument/DOMDXPath的解决方案:

$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解析相关的问题。

1)2)该字符串似乎没有出现在提供的URL上。(源代码中的字符串对类定义使用单引号封装,以供参考)。@JonStirling,对于您的#2注释,该字符串确实存在于第行中895@CodeGodie不,没有。仔细看。啊。。它确实存在,只是它有单引号
而不是双引号