简体   繁体   English

用php替换动态链接

[英]Replace dynamic links with php

I wan to replace dynamic links in text with text like: 我想用以下文本替换文本中的动态链接:
if the links are 如果链接是

<a href="show.php?id=3">Number three</a>
<a href="show.php?id=4">Number four</a>
<a href="show.php?id=1">StackOverflow</a>
<a href="view.php?id=9">Foo</a>

I want this returned 我希望这个退货

Number three
Number four
StackOverflow
<a href="view.php?id=9">Foo</a>

What will be the perfect regex for this, I tried handful of regex but they just don't work. 什么是完美的正则表达式,我尝试了一些正则表达式,但它们只是不起作用。
EDIT: 编辑:

String contains other links like view.php?id=5 and I don't want to replace them. 字符串包含其他链接,例如view.php?id=5 ,我不想替换它们。

This should work: 这应该工作:

$regex = '~<a href="show.php\?id=\d+">([^<]*)</a>~Ui';
$output = preg_replace($regex, '$1', $input);
$html = '
    <a href="show.php?id=3">Number three</a>
    <a href="show.php?id=4">Number four</a>
    <a href="show.php?id=1">StackOverflow</a>
    <a href="view.php?id=9">Foo</a>
';

$doc = new DOMDocument();
$doc->loadHTML($html);

foreach ($doc->getElementsByTagName("a") as $a) {
    if (strpos($a->getAttribute("href"), "show.php") === 0) {
        echo $a->nodeValue . "\n";
    } else {
        echo $doc->saveHTML($a) . "\n";
    }
}

will output: 将输出:

Number three
Number four
StackOverflow
<a href="view.php?id=9">Foo</a>

You need to use a negative lookahead based regex. 您需要使用基于负前瞻的正则表达式。

<a href="(?!view\.php\?id=\d+")[^"]*">([^<>]*)</a>

DEMO 演示

$re = "~<a href=\"(?!view\\.php\\?id=\\d+\")[^\"]*\">([^<>]*)</a>~m";
$str = "<a href=\"show.php?id=3\">Number three</a>\n<a href=\"show.php?id=4\">Number four</a>\n<a href=\"show.php?id=1\">StackOverflow</a>\n<a href=\"view.php?id=9\">Foo</a>";
$subst = "$1";

$result = preg_replace($re, $subst, $str);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM