我试过学习这个,但不管出于什么原因,它都不起作用。
我有以下内容:
其代码为:
<li><b>
text here:
</b>
5.3 x 6.0 x 40 metres
</li>
这个HTML在一个变量中,我们称之为$dimensions我正试图用preg_match_all提取5.3 x 6.0 x 40 metres
,理想情况下提取尺寸和测量值,但我很难响应结果。它表示,尽管匹配的大小为5,但每次数组转换为字符串都会出错。有什么想法吗?
preg_match_all('/'<li'>([0-9]*'.*[0-9]*)x([0-9]*'.*[0-9]*)x([0-9]*'.*[0-9]*)
's*([a-zA-Z]*)'<'/li'>/',$dimensions,$matches,PREG_PATTERN_ORDER);
echo sizeof($matches);
echo($matches[0]);
编辑:
正如下面的答案所建议的:有人说使用var_dump($matches)来查看数组包含什么。。。原来我有4个空数组,这就引出了下一个问题。我的preg_match_all出了什么问题?
array (size=5)
0 =>
array (size=0)
empty
1 =>
array (size=0)
empty
2 =>
array (size=0)
empty
3 =>
array (size=0)
empty
4 =>
array (size=0)
empty
我建议不要首先使用pregmatch,使用html DOMdocument
并使用XPath查询节点,将结果限制为文本本身,然后使用preg_match_all
$content = "<li>
<b>
text here:
</b>
5.3 x 6.0 x 40 metres
</li>";
$doc = new DOMDocument();
$doc->loadHTML($content);
$xp = new DOMXPath($doc);
foreach($xp->query('/html/body/li/text()') as $child){
$dimensionText = $child->textContent;
preg_match_all('!'d+!', $dimensionText, $matches);
print_r($matches);
}
以上内容将为您提供每个维度的数值
尝试使用var_dump检查数组包含的内容:
<?php
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
?>
$dimensions = '<li><b>
text here:
</b>
5.3 x 6.0 x 40 metres
</li>';
$t = simplexml_load_string($dimensions);
echo $t;
它将提取5.3 x 6.0 x 40米,而不是您获得的值