如果你在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>';
答案 0 :(得分:1)
这应该这样做:代码中的解释。
<?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>
?>