PHP preg_replace:找到链接并添加一个#hash它? [英] php preg_replace: find links and add a #hash to it?
问题描述
我有以下结构...
$ output ='< li>< a href =http:// forum.example.org> Something< / a>< / li>'
实际上,$ output会保存多个列表项。
对每个链接href应用#hash的最佳和最简单的方法是什么?如... ...
< li>< a href =http://forum.example.org#something>有什么想法如何解决?
$ b $ b
编辑:顺便说一句,它应该始终是相同的#hash不像你在上面这个例子中想的那样,#something等于链接的名字。因此,它应该是每个链接#something。
add_filter('wp_list_pages','add_hash'); / *将#hash添加到wp_list_pages()函数* /
函数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;
}
$ dom = new DOMDocument();
$ dom-> loadHTML($ str); //改变输入变量
$ a_tags = $ dom-> getElementsByTagName('a');
foreach($ a_tags as $ a)
{
$ value = $ a-> getAttribute('href');
$ a-> setAttribute('href',$ value。'#something');
}
//获取新文档:$ dom-> saveHTML()
编辑:
在上面的代码中,您需要更改:
$ dom-> saveHTML();
return $ output;
收件人:
return $ dom-> saveHTML();
}
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;
}
$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();
}
这篇关于PHP preg_replace:找到链接并添加一个#hash它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!