PCRE 将十六进制 #334455 替换为 #345

发布于 2024-08-02 16:28:39 字数 467 浏览 2 评论 0原文

我正在编写一个函数,用短十六进制编码颜色 (#334455) 替换长十六进制编码颜色 (#345)。仅当十六进制中的每种颜色是 17 的倍数(每个十六进制对包含相同的字符)时才能执行此操作。

例如,#EEFFCC 替换为 #EFC,但 #EDFFCC 不替换为任何内容。

我想通过单个 preg_replace() 调用来完成此操作,而不需要任何自定义回调。

我已经尝试过这个:

$hex = preg_replace('/([0-f]){2}([0-f]){2}([0-f]){2}/i', '\1\2\3', $hex);

但这会缩短所有十六进制,而不仅仅是每对中具有相同字符的十六进制。我不知道如何只匹配相同字符对。

请帮忙。

I'm writing a function that replaces long hex coded color (#334455) with short one (#345). This can be only done when each color in hex is multiple of 17 (each hex pair consists of the same characters).

e.g. #EEFFCC is replaced with #EFC, but #EDFFCC isn't replaced with anything.

I want to make this with single preg_replace() call without any custom callbacks.

I've already tried this:

$hex = preg_replace('/([0-f]){2}([0-f]){2}([0-f]){2}/i', '\1\2\3', $hex);

But that shortens all hexes, not just the hexes with same characters in each pair. I can't figure out how to match only pairs of same character.

Please help.

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

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

发布评论

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

评论(1

2024-08-09 16:28:39

试试这个 - 你只需要使用 反向引用在比赛本身

$hex = preg_replace('/([0-f])\1([0-f])\2([0-f])\3/i', '\1\2\3', $hex);

Try this - you just need to use the backreferences in the match itself

$hex = preg_replace('/([0-f])\1([0-f])\2([0-f])\3/i', '\1\2\3', $hex);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文