替换字符串中的冒号,除非它们是不合格子字符串的一部分

发布于 2024-11-27 23:01:22 字数 440 浏览 3 评论 0原文

我想将 : 替换为 \xEF\xBC\x9A 但是,我不想对 之后的 : 执行此操作httphttps 以及格式为 @[{numbers}:{numbers}:{some text}] 的字符串。 我所拥有的并没有真正起作用,因为 (? 不会检查其后面的内容。我当前的实现仅适用于 @[1:2:text] 之类的内容。

$string = preg_replace(
    '#(?<!https)(?<!http)(?<!@\[\d)(?<!@\[\d:\d):#',
    "\xEF\xBC\x9A",
    $string
);

I would like to replace : with \xEF\xBC\x9A however, I do not want to do this for : that follows http, https, and string with the format of @[{numbers}:{numbers}:{some text}].
What I have doesn't really work as (?<!@\[\d) does not check what's after it. My current implementation only work for something like @[1:2:text].

$string = preg_replace(
    '#(?<!https)(?<!http)(?<!@\[\d)(?<!@\[\d:\d):#',
    "\xEF\xBC\x9A",
    $string
);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

倦话 2024-12-04 23:01:22

试试这个:

preg_replace('/(@\[\d+:\d+:[^]]*]|https?:)|:/e', '"$1"?"$1":"\xEF\xBC\x9A"', $string);

Try this:

preg_replace('/(@\[\d+:\d+:[^]]*]|https?:)|:/e', '"$1"?"$1":"\xEF\xBC\x9A"', $string);
長街聽風 2024-12-04 23:01:22

试试这个正则表达式:

(?<!@\[(?::?[\d]{0,5}){1,2})(?<!https?):

它应该与此处的第一个和第二个“:”实例匹配。

: test: http: @[1:2:text]

使用示例:

$string = preg_replace('/(?<!@\[(?::?[\d]{0,5}){1,2})(?<!https?):/', '\xEF\xBC\x9A', $string);

Try this regex:

(?<!@\[(?::?[\d]{0,5}){1,2})(?<!https?):

It should match the first and second instances of ':' here.

: test: http: @[1:2:text]

Usage Sample:

$string = preg_replace('/(?<!@\[(?::?[\d]{0,5}){1,2})(?<!https?):/', '\xEF\xBC\x9A', $string);
原谅我要高飞 2024-12-04 23:01:22

匹配不应改变的表达式,然后使用 (*SKIP)(*FAIL) 取消它们的资格——这比尝试避免匹配它们要简单得多。然后匹配任何非不合格的冒号并将其替换为所需的字符串。

代码:(演示

$string = <<<TEXT
foo : test: http: @[1:2:text] http://example.com 3:4
TEXT;

echo preg_replace(
    '/(?:https?:|@\[\d+:\d+:[^\]]+)(*SKIP)(*FAIL)|:/',
    '\xEF\xBC\x9A',
    $string
);

输出:

foo \xEF\xBC\x9A test\xEF\xBC\x9A http: @[1:2:text] http://example.com 3\xEF\xBC\x9A4

Match the expressions that should not be mutated then disqualify them with (*SKIP)(*FAIL) -- this is far simpler than trying to avoid matching them. Then match any non-disqualified colon and replace it with the desired string.

Code: (Demo)

$string = <<<TEXT
foo : test: http: @[1:2:text] http://example.com 3:4
TEXT;

echo preg_replace(
    '/(?:https?:|@\[\d+:\d+:[^\]]+)(*SKIP)(*FAIL)|:/',
    '\xEF\xBC\x9A',
    $string
);

Output:

foo \xEF\xBC\x9A test\xEF\xBC\x9A http: @[1:2:text] http://example.com 3\xEF\xBC\x9A4
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文