Feb.05

Preg Match php function Example

Check weather the string is hex color combination or not.  This type of logic is required to filter the color picker value.

The preg_match php function is useful for this type of problem.

For example :

[ $color = ‘#001ABC’;  ] [ $color = ‘001ABC’;  ] [ $color = ‘#mnop01’;  ]

The above three are stored color combination of value. from these we only have visible the color value with starting # with combination of [a to f] and [1-9]. If we find these combination on the string then we set received color from value otherwise further processing required.

The preg_match(‘/^#[a-f0-9]{6}$/i’, $color)  function treat checking all the string $color variable with comparison with start string # and string set of a to f and 1 to 9 with sting must be 6 character length {6}.

//Check for a hex color string ‘#001ABC’
$color = ‘#001ABC’;
if (preg_match(‘/^#[a-f0-9]{6}$/i’, $color))
{
//hex color is valid
//Verified hex color with first string  #
$fix_color = $color;
}
//Check for a hex color string without hash ‘c1c2b4’
else if (preg_match(‘/^[a-f0-9]{6}$/i’, $color))
{
//hex color  combination is right but first string need to #
$fix_color = ‘#’ . $color;
}
else
{
// Set my default color combination
$fix_color = ‘#000’;
}
echo $fix_color;

[ $color = ‘#001ABC’;  ]

// This gives true case. It satisfies # string with string combination with 6 letters. It goes to if first condition

[ $color = ‘001ABC’;  ]

// It has only satisfies else if condition because it have not the start letter # Returns string adding with # on the front string go to second else if condition

[ $color = ‘#mnop01’;  ]

// Returns default value go to else condition on example

Share this Story:
  • facebook
  • twitter
  • gplus

Leave a comment

Facebook Comment