简体   繁体   English

PHP RegEx替换所有非图像的URL

[英]PHP RegEx Replace All URLs That Aren't Images

I'm currently using this regular expression to capture all URLs in a string, which could be multiple lines and contain any other sort of text, which is working perfectly for normal URLs. 我目前正在使用这个正则表达式来捕获字符串中的所有URL,这些URL可以是多行并包含任何其他类型的文本,这对于普通URL非常有效。 But I want to replace image URLs in a different way, so my current expression can't match those URLs. 但我想以不同的方式替换图像URL,因此我当前的表达式无法匹配这些URL。

My current expression is 我现在的表达是

(https?:\/\/([-\w\.]+[-\w])+(:\d+)?(\/([\w\/_\.#-]*(\?\S+)?[^\.\s])?)?)

But I don't want it to match URLs that end with (jpe?g|png|gif), and I haven't been able to figure out exactly how to use the RegEx negative lookaheads. 但是我不希望它匹配以(jpe?g | png | gif)结尾的URL,而我还没弄清楚如何使用RegEx负向前瞻。

Really, it would be easier to just check the urls afterwards by matching all urls and then checking them. 实际上,通过匹配所有网址然后检查它们来检查网址会更容易。 Or use preg_replace_callback which would allow you to check additional stuff on the match and add additional logic to check what type of url it is. 或者使用preg_replace_callback ,它允许您检查匹配上的其他内容并添加其他逻辑以检查它是什么类型的URL。 You just switch the replacement value with a callback and whatever is returned from the callback is what is replaced. 您只需使用回调切换替换值,并且从回调返回的内容是替换的内容。

But, if you wanted to use a single regex, put something like this at the start of your pattern: (?!\\S+(?:png|gif|jpe?g)) which will force a url to not match if it has .(png|gif|jpe?g) anywhere in the string. 但是,如果你想使用一个正则表达式,在你的模式的开头加上这样的东西: (?!\\S+(?:png|gif|jpe?g))如果有的话会强制网址不匹配.(png|gif|jpe?g)字符串中的任何地方。

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

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