使用 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;
输入:
<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>
输出:
<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>