[英]How to remove http and https without img src
code: 码:
$str = 'http://www.google.com <img src="http://placehold.it/350x150" />';
$str = preg_replace('/\b(https?):\/\/[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i', '', $str);
echo $str;
output: 输出:
<img src="" />
i need this output: 我需要这个输出:
<img src="http://placehold.it/350x150" />
how can i do it? 我该怎么做?
thanks for help. 感谢帮助。
Your pattern 你的模式
/\b(https?):\/\/[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i
removes all URLs (in the string) which start with protocol http
or https
. 删除所有以协议
http
或https
开头的URL (在字符串中) 。 So when you apply it on your string, it will remove both that URL which is in the beginning of the string and that URL which is as src
of <img>
. 因此,当您将其应用于字符串时,它将删除位于字符串开头的URL和作为
<img>
src
的URL。 So you have to use ^
in the beginning of your pattern: 所以你必须在模式的开头使用
^
:
$str = 'http://www.google.com <img src="http://placehold.it/350x150" />';
$str = preg_replace('/^\b(https?):\/\/[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i', '', $str);
echo $str;
Or simply get what you need like this: 或者简单地得到你需要的东西:
/(<img.*\/>)/i
I also think that DOMDocument
and DOMXPath
are preferable tools for parsing HTML markup. 我还认为
DOMDocument
和DOMXPath
是解析HTML标记的首选工具。
But just in your particular case, here is solution with regexp negative lookbehind assertion : 但只是在你的特定情况下,这里是regexp 负向lookbehind断言的解决方案:
$str = 'http://www.google.com <img src="http://placehold.it/350x150" /> http://www.google.com.ua';
$str = preg_replace('/(?<!src=\")(https|http):\/\/[^\s]+\b/i', '', $str);
print_r($str); // <img src="http://placehold.it/350x150" />
This will remove all urls excepting those which are inside an img
src attribute 这将删除除
img
src属性内的所有URL之外的所有URL
Try: 尝试:
<[^>]*(*SKIP)(*FAIL)|\\b(https?):\\/\\/[-A-Z0-9+&@#\\/%?=~_|$!:,.;]*[A-Z0-9+&@#\\/%=~_|$]
The <[^>]*
catches all the things within an unclosed <
and (*SKIP)(*FAIL)|
<[^>]*
捕获未闭合的所有内容<
和(*SKIP)(*FAIL)|
skips them. 跳过它们。
The rest is your regex. 剩下的就是你的正则表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.