Replace www.example.com w/ <a href=“http://www.example.com”>www.example.com</a>

自古美人都是妖i 提交于 2019-12-02 17:58:02

问题


I am not very good at regex, but I need to convert the following example from this

<li>Creations by Carol - www.driedfloralcreations.com</li>

to

<li>Creations by Carol - <a href="http://www.driedfloralcreations.com" rel="external">www.driedfloralcreations.com</a></li>

回答1:


If you're only looking for URLs in <li> elements formatted like the one in your question, it should be much simpler than a lot of the other suggested solutions. You don't really need to validate your URLs, I assume, you just want to take a list of site names and URLs and turn the URLs into links.

Your search pattern could be:

<li>(.+) - (https?:\/\/)?(\S+?)<\/li>

And the replace pattern would be:

<li>$1 - <a href="(?2:$2:http\://)$3" rel="external">$3</a></li>

Just tested the find/replace out in TextMate and it worked nicely. It addes http:// if it isn't already present, and otherwise assumes that whatever is after the - is a URL as long as it doesn't contain a space.

For testing out regular expressions, Rubular is a great tool. You can paste in some text, and it'll show you what matches as you type your regex. It's a ruby tool, but TextMate uses the same regex syntax as ruby.




回答2:


How about this in PHP?

$string = '<li>Creations by Carol - www.driedfloralcreations.com</li>';
$pattern = '/(www\.[a-z\d-\.]+\.[a-z]+)/i';
$replacement = '<a href="http://$1" rel="external">$1</a>';
echo preg_replace($pattern, $replacement, $string);

Assumes your links are always www.something.extension.




回答3:


You have to be really clear about how much information you need to give the regex to avoid false positives.

For example is the pattern www.something.somethingelse enough? are there other www in the file that would get caught?

maybe <li> something - somethingelse</li> is the correct match. We cannot guess without knowing your whole file. There might be other <li> in there that you don't want to change.




回答4:


www\.[a-zA-Z0-9_-]+\.(fr|com|org|be|biz|info|getthelistsomewhere)


来源:https://stackoverflow.com/questions/1562721/replace-www-example-com-w-a-href-http-www-example-comwww-example-com-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!