Finetune Regex to skip tags

左心房为你撑大大i 提交于 2019-12-31 07:38:25

问题


Code must skip existing links, <img>'s src values (or something like that)

public function convertUrlsToLinks($text){
    return preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.-]*(\?\S+)?)?)?)@', '<a href="$1" target="_blank">$1</a>', $text);
}

Can't figure out, what I need to modify in this function?


回答1:


Add a small part to your regex that checks if your regex isn't 'inside' a tag. So it should be

     <tag>HERE</tag> 

and not

     <tag src="HERE"></tag>.

Since a url will always be INSIDE the html tag it should work if you finetune your regex to this use. I'm not a pro with regex' so can't help you more than this, but I think this should get you in the right direction.



来源:https://stackoverflow.com/questions/11958903/finetune-regex-to-skip-tags

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