php正则表达式和替换


php regular expression and replace

使用php和一个正则表达式可以执行以下操作。如果超链接的顶级域与数组中给定的tld名称匹配,则获取内容中的所有超链接并重写它们。

现在有一个正则表达式,它重写给定内容中的所有超链接

preg_replace('/<a(.*)href="([^"]*)"(.*)>/','<a$1href="goto.php?url=$2"$3>', $content);

示例

$tld = array("http://www.example.com","http://www.test.com");
if <a href="www.example.com">example</a> than <a href="/goto.php?url= www.example.com"</a>;

您可能需要稍微固化您的正则表达式。。。

$pattern = <<<EOL
/<a([^>]+)href's*='s*(['" ]?)([^"'> ]*)(['" ]?)([^>]*)>/si
EOL;
$replacement = "<a$1href='goto.php?url=$3'$5>";
preg_replace($pattern, $replacement, $content);

现在无法对此进行测试,因此可能存在拼写错误。。。