1

If you have this string in PHP:

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

Is it possible to find the rgb occurrences and change them to hexadecimal so the new string is:

 $new_str = 'content<div style="color:#000000;">more content</div><div style="color: #ffffff;">more content</div>';
Sometip
  • 332
  • 1
  • 10
  • 1
    you question is two-fold, first get the color attribute first, you can use regex, then the conversion, already has solution in SO https://stackoverflow.com/a/32977705/3859027 – Kevin May 17 '18 at 01:19

1 Answers1

1

This should do it: Explanation in code.

<?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>

?>

Reference: Convert RGB to hex color values in PHP

icecub
  • 8,615
  • 6
  • 41
  • 70