假设您要查找的每个特定文本仅映射到单个链接(听起来像您这样做),您可以构建一个关联查找数组。我自己也遇到了这个需求。以下是我的处理方式。这样您就不需要每次都循环遍历所有链接。
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";
}