简体   繁体   English

用PHP修改超链接

[英]Modify hyperlinks with PHP

I'm using a regular expression to turn URLs in blog comments into clickable hyperlinks. 我使用正则表达式将博客评论中的URL转换为可单击的超链接。 However, i also want to do the opposite: 但是,我也想做相反的事情:

Since i allow certain html tags (but not <a> ), if somebody types in a hyperlink, i'd like to change it from: 由于我允许某些html标签(但不允许<a> ),因此如果有人键入超链接,我想将其更改为:

<a href="http://www.example.com">My Link</a>

into 进入

My Link : http://www.example.com 我的链接http : //www.example.com

where the generated code is: 生成的代码是:

<p><b>My Link:</b> <a href="http://www.example.com" rel="nofollow">http://www.example.com</a></p>

Thanks! 谢谢!

Try with this. 试试这个。

function find_links($url){
    $pattern = '/<a (.*?)href="(.*?)\/\/(.*?)"(.*?)>(.*?)<\/a>/i';
    $url = preg_replace_callback($pattern, 'process_links',$url);
    return $url;
}

function process_links($m){
    return "{$m[5]} <a href=\"{$m[2]}//{$m[3]}\" rel=\"nofollow\">{$m[2]}//{$m[3]}</a>";
}

$links = find_links('<a href="http://www.example.com">My Link</a>');

EDIT: Oops! 编辑:糟糕! I didn't quite gave answer to the OP's question. 我没有完全回答OP的问题。

Parsing an irregular language with a regular expression is the short road to failure. 用正则表达式解析不规则语言是通往失败的捷径。 Use a proper HTML parser instead. 改用正确的HTML解析器

You just need to search for either www or http then convert that text until you reach a space to the url. 您只需要搜索www或http,然后转换该文本,直到到达URL空格为止。

Something like:
    $startPos = strpos( $input, "http" );
    $endPos = strpos( $input, " ", $startPos );
    $urlText = substr( $input, $startPos, $endPos - $startPos );

I think I miss read your question a bit... something similar to the above but looking for instead. 我想我有点想念您的问题...与上述类似,但正在寻找。

Well, if you don't mind some CSS (and the implementation variances of browsers): 好吧,如果您不介意一些CSS(以及浏览器的实现差异):

a {font-weight: bold; }
a:after {content: " (" attr(href) ") "; }

Should partly achieve your aims, though it won't remove the link while showing the link text. 尽管可以在显示链接文本时不会删除该链接,但应该可以部分实现您的目标。 So, really I guess it doesn't. 所以,真的我猜不是。 Sorry... 抱歉...

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

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