将 src 属性值从相对 URL 替换为绝对 URL

发布于 2024-08-19 15:44:45 字数 348 浏览 8 评论 0原文

这是一个简单的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

┈┾☆殇 2024-08-26 15:44:45

这真是一个混乱的正则表达式。您到底想实现什么目标?看起来如果 URL 不是以 http 或 https 开头,您想要添加域吗?如果是这样,那么你就有点偏离了:

$string = preg_replace('/src=(\'|")?(?!htts?:)/i', 'src="http://domain.com/');

应该更接近目标。

这个正则表达式有什么作用?它查找:

  • src=
  • (可选)后跟 '"
  • not 后跟 http:< /code> 或 https:
  • 全部完成,不区分大小写

注意: {?!...) 被称为否定前瞻 是零宽度断言 的一个示例。这里意味着它不消耗任何输入。在这种情况下,它意味着“后面没有...”。

它会查找:

  • src=
  • one 或更多 '"
  • 个字符 任何 (http:|https:) 的任何一个字符 (这就是 [^...] 构造的含义)
  • 所有大小写不敏感

注意:

[^(http:|https:)]

相当于:

[^():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:

$string = preg_replace('/src=(\'|")?(?!htts?:)/i', 'src="http://domain.com/');

should be a lot closer to the mark.

What does this regex do? It looks for:

  • src=
  • optionally followed by either ' or "
  • not followed by http: or https:
  • all done case insensitive

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=
  • one or more ' or " characters
  • any one character that isn't any of (http:|https:) (that's what the [^...] construct means)
  • all case insensitive

Note:

[^(http:|https:)]

is equivalent to:

[^():https]

meaning any character that is not one of those characters.

雾里花 2024-08-26 15:44:45

构造 [^(http:|https:)] 不正确。它匹配除 (, h, t, p, :, |s)

The construct [^(http:|https:)] is incorrect. It matches any character except (, h, t, p, :, |, s, or ).

审判长 2024-08-26 15:44:45
$string = 'src="index.php'; $string = preg_replace("/src=('|\")?(?!htts?:)/i", "src=\"http://domain.com/", $string); echo $string;

试试这个:我自己测试过

$string = 'src="index.php'; $string = preg_replace("/src=('|\")?(?!htts?:)/i", "src=\"http://domain.com/", $string); echo $string;

try this: I tested it myself

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文