在PHP中,我使用的是Simple HTML DOM Parser类。
我有一个包含多个A-tag的HTML文件。
现在我需要找到里面有特定文字的标签。
例如:
$html = "<a id='tag1'>A</a>
<a id='tag2'>B</a>
<a id='tag3'>C</a>
";
$dom = str_get_html($html);
$tag = $dom->find("a[plaintext=B]");
上述示例不起作用,因为明文只能用作属性。
有什么想法吗?
答案 0 :(得分:3)
<?php
include("simple_html_dom.php");
$html = "<a id='tag1'>A</a>
<a id='tag2'>B</a>
<a id='tag3'>C</a>
";
$dom = str_get_html($html);
$select = NULL;
foreach($dom->find('a') as $element) {
if ($element->innertext === "B") {
$select = $element;
break;
}
}
?>
答案 1 :(得分:0)
假设您要查找的每个特定文本仅映射到单个链接(听起来像您这样做),您可以构建关联查找数组。我自己刚遇到这个需要。这是我处理它的方式。这样您就不需要每次都循环遍历所有链接。
function populateOutlines($htmlOutlines)
{
$marker = "courses";
$charSlashFwd = "/";
$outlines = array();
foreach ($htmlOutlines->find("a") as $element)
{
// filter links for ones with certain markers if required
if (strpos($element->href, $marker) !== false)
{
// construct the key the way you need it
$dir = explode($charSlashFwd, $element->href);
$code = preg_replace(
"/[^a-zA-Z0-9 ]/", "", strtoupper(
$dir[1]." ".$dir[2]));
// insert the lookup entry
$outlines[$code] = $element->href;
}
}
return $outlines;
}
// ...stuff...
$htmlOutlines = file_get_html($urlOutlines);
$outlines = populateOutlines($htmlOutlines);
// ...more stuff...
if (array_key_exists($code, $outlines)) {
$outline = $outlines[$code];
} else {
$outline = "n/a";
}