Comment supprimer les liens en double d'une page sauf la première
-
12-11-2019 - |
Question
J'ai un problème avec certains contenus, qui ont le même lien encore et encore, donc je souhaite supprimer tous les liens en double sauf un seul, avez une idée de quelqu'un comment faire cela ????
Voici mon code qui supprimer tous les liens
function anchor_remover($page) {
$filter_text = preg_replace("|<<blink>a *<blink>href=\<blink>"(.*)\">(.*)</a>|","\\2",$page);
return $filter_text;
}
add_filter('the_content', 'anchor_remover');
En gros, j'ai besoin de cela pour WordPress, pour filtrer le contenu et supprimer des liens en double ne doit avoir qu'un seul lien.
La solution
Utilisation de Preg_replace_callback:
<?php
/*
* vim: ts=4 sw=4 fdm=marker noet
*/
$page = file_get_contents('./dupes.html');
function do_strip_link($matches)
{
static $seen = array();
if( in_array($matches[1], $seen) )
{
return $matches[2];
}
else
{
$seen[] = $matches[1];
return $matches[0];
}
}
function strip_dupe_links($page)
{
return preg_replace_callback(
'|<a\s+href="(.*?)">(.*?)</a>|',
do_strip_link,
$page
);
}
$page = strip_dupe_links($page);
echo $page;
entrée:
<html>
<head><title>Hi!</title></head>
<body>
<a href="foo.html">foo</a>
<a href="foo.html">foo</a>
<a href="foo.html">foo</a>
<a href="foo.html">foo</a>
<a href="foo.html">foo</a>
<a href="foo.html">foo</a>
<a href="foo.html">foo</a>
<a href="foo.html">foo</a>
<a href="foo.html">foo</a>
<a href="foo.html">foo</a>
<a href="bar.html">bar</a>
</body>
</html>
sortie:
<html>
<head><title>Hi!</title></head>
<body>
<a href="foo.html">foo</a>
foo
foo
foo
foo
foo
foo
foo
foo
foo
<a href="bar.html">bar</a>
</body>
</html>
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow