将 src 属性值从相对 URL 替换为绝对 URL
这是一个简单的 preg_replace()
调用:
$string = 'src="index.php';
$string = preg_replace("/(src=('|\")+[^(http:|https:)])/i", "src=\"http://example.com/", $string);
echo $string;
我期望结果是 src="http://example.com/index.php
但结果是 src="http://example.com/ndex.php
.
我一定在这里错过了一些东西..
Here's a simple preg_replace()
call:
$string = 'src="index.php';
$string = preg_replace("/(src=('|\")+[^(http:|https:)])/i", "src=\"http://example.com/", $string);
echo $string;
I expect the result to be src="http://example.com/index.php
but it turns out to be src="http://example.com/ndex.php
.
I must be missing something here..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这真是一个混乱的正则表达式。您到底想实现什么目标?看起来如果 URL 不是以 http 或 https 开头,您想要添加域吗?如果是这样,那么你就有点偏离了:
应该更接近目标。
这个正则表达式有什么作用?它查找:
src=
'
或"
http:< /code> 或
https:
注意:
{?!...)
被称为否定前瞻 是零宽度断言 的一个示例。这里意味着它不消耗任何输入。在这种情况下,它意味着“后面没有...”。它会查找:
src=
'
或"
(http:|https:) 的任何一个字符
(这就是[^...]
构造的含义)注意:
相当于:
表示任何不<的字符/em> 这些字符之一。
That's a really messed up regex. What are you trying to achieve exactly? It looks like if the URL doesn't start with http or https you want to add the domain? If so, you're quite a bit off:
should be a lot closer to the mark.
What does this regex do? It looks for:
src=
'
or"
http:
orhttps:
Note:
{?!...)
is called a negative lookahead and is one example of a zero-width assertion. "Zero-width" here means that it doesn't consume any of the input. In this case it means "not followed by ...".What does your regex do? It looks for:
src=
'
or"
characters(http:|https:)
(that's what the[^...]
construct means)Note:
is equivalent to:
meaning any character that is not one of those characters.
构造
[^(http:|https:)]
不正确。它匹配除(
,h
,t
,p
,:
,|
、s
或)
。The construct
[^(http:|https:)]
is incorrect. It matches any character except(
,h
,t
,p
,:
,|
,s
, or)
.试试这个:我自己测试过
try this: I tested it myself