Back

https://regex101.com/


add html tags to strings using regex

/#[a-fA-F0-9]{3,4}/g   : finds any '#fc0'
/'#[a-fA-F0-9]{3,4}'/g
/'#[a-fA-F0-9]{3}'/g

/'#[a-fA-F0-9]{3}'|'#[a-fA-F0-9]{4}'|'#[a-fA-F0-9]{6}'|'#[a-fA-F0-9]{8}'/g

replace with : in ecmaScript : javascript 
$&
regex last match in php

php : $0
it returns : preg_replace(pattern, replacement, input)

  function color_the_hex_codes($x) {
    
    $pattern = "/#[a-fA-F0-9]{8}|#[a-fA-F0-9]{6}|#[a-fA-F0-9]{4}|#[a-fA-F0-9]{3}/"; // there is no modifier g
    $replacement = "<span style='padding: 0.15em; font-weight: bold; color: $0; background-color: #333;'>$0</span>";
    $y = preg_replace($pattern, $replacement, $x);
    
    return $y;
  }

  $x = "a function like color('#fc0') or stroke('#58fa')";
  echo color_the_hex_codes($x);
  function color_the_hex_codes($x) {
    
    $pattern = "/#[a-fA-F0-9]{8}|#[a-fA-F0-9]{6}|#[a-fA-F0-9]{4}|#[a-fA-F0-9]{3}/"; // there is no modifier g
    
    // $pattern = "/#[a-fA-F0-9]{6}|#[a-fA-F0-9]{3}/"; // there is no modifier g
    $replacement = "$0";
    // $y = preg_replace($pattern, $replacement, $x);
    
    function callback($matches) {
      
      $hex = $matches[0];
      
      if (strlen($hex) == 9) {
        $hex = substr($hex, 0, 7);
      }
      
      if (strlen($hex) == 5) {
        $hex = substr($hex, 0, 4);
      }
      
      return "" . strtoupper($hex) . "";
    }
    
    $y = preg_replace_callback($pattern, 'callback', $x);
    

    
    return $y;
  }