如何从字符串中获取 rgb 符号并将它们转换为十六进制?



如果你在PHP中有这个字符串:

$str = 'content<div style="color:rgb(0,0,0);">more content</div><div style="color: rgb(255,255,255);">more content</div>';

是否可以找到 rgb 出现并将它们更改为十六进制,因此新字符串为:

$new_str = 'content<div style="color:#000000;">more content</div><div style="color: #ffffff;">more content</div>';

这应该做到: 代码中的解释。

<?php
$input = 'content<div style="color:rgb(0,0,0);">more content</div><div style="color: rgb(255,255,255);">more content</div>';
$result = preg_replace_callback(
// Regex that matches "rgb("#,#,#");" and gets the #,#,#
'/rgb((.*?));/',
function($matches){
// Explode the match (0,0,0 for example) into an array
$colors = explode(',', $matches[1]);
// Use sprintf for the conversion
$match = sprintf("#%02x%02x%02x;", $colors[0], $colors[1], $colors[2]);
return $match;
},
$input
);
print_r($result); //content<div style="color:#000000;">more content</div><div style="color: #ffffff;">more content</div>
?>

参考:在 PHP 中将 RGB 转换为十六进制颜色值

最新更新