Come rimuovo i collegamenti duplicati da una pagina tranne prima
-
12-11-2019 - |
Domanda
Ho un problema con alcuni contenuti, che hanno lo stesso link ancora e ancora, quindi voglio rimuovere tutti i collegamenti duplicati tranne un singolo, ho idea di come farlo ????
Ecco il mio codice che rimuove tutti i collegamenti
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');
Fondamentalmente ne ho bisogno per WordPress, per filtrare il contenuto e rimuovere i collegamenti duplicati dovrebbe avere un solo collegamento.
Soluzione
Utilizzando 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;
Ingresso:
<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>
Produzione:
<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>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow