您好我的Regex代码有问题,我用它来使用PHP从HTML标签中获取值.我有以下字符串可能:
<span class="down last_position">xyz</span>
<span class="up last_position">xyz</span>
<span class="last_position new">xyz</span>
Run Code Online (Sandbox Code Playgroud)
我有以下preg_match命令:
preg_match('#<span class="last_position.*?">(.+)</span>#', $string, $matches);
Run Code Online (Sandbox Code Playgroud)
这几乎只涉及案例#3.所以我想知道在last_position前面需要添加什么才能使所有情况都成为可能..?
非常感谢..
编辑:对于所有想知道要匹配什么值的人:"xyz"
避免使用正则表达式来解析HTML,因为它可能容易出错.使用DOM解析器可以更好地解决您的特定UseCase:
$html = <<< EOF
<span class="down last_position">xyz</span>
<span class="up last_position">xyz</span>
<span class="last_position new">xyz</span>
EOF;
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html); // loads your html
$xpath = new DOMXPath($doc);
$nodeList = $xpath->query("//span[contains(@class, 'last_position')]/text()");
for($i=0; $i < $nodeList->length; $i++) {
$node = $nodeList->item($i);
var_dump($node->nodeValue);
}
Run Code Online (Sandbox Code Playgroud)
OUTPUT:
string(3) "xyz"
string(3) "xyz"
string(3) "xyz"
Run Code Online (Sandbox Code Playgroud)