问题
i have the following structure...
$output = '<li><a href="http://forum.example.org">Something</a></li>'
Actually $output holds multiple list-items.
What's the best and easiest way to apply a #hash to each links href? as in...
<li><a href="http://forum.example.org#something">Something</a></li>
Any idea how to solve that?
edit: btw it should always be the same #hash not as you might think in this example above, the #something is equal to the name of the link. So it should be #something for each link.
add_filter('wp_list_pages', 'add_hash'); /*Add #hash to wp_list_pages() function*/
function add_hash($output) {
$dom = new DOMDocument();
$dom->loadHTML($output);
$a_tags = $dom->getElementsByTagName('a');
foreach($a_tags as $a)
{
$value = $a->getAttribute('href');
$a->setAttribute('href', $value . '#b');
}
$dom->saveHTML();
return $output;
}
回答1:
$dom = new DOMDocument();
$dom->loadHTML($str); // Change to input variable
$a_tags = $dom->getElementsByTagName('a');
foreach($a_tags as $a)
{
$value = $a->getAttribute('href');
$a->setAttribute('href', $value . '#something');
}
// Get the new document with: $dom->saveHTML()
Edit:
In your above code, you need to change:
$dom->saveHTML();
return $output;
}
To:
return $dom->saveHTML();
}
来源:https://stackoverflow.com/questions/5317503/php-preg-replace-find-links-and-add-a-hash-to-it