Search code examples
phpcssarrayspreg-splitdelimited

Parse inline style attribute string and get index of a specific attribute name


I have the below php array $tempStyleArray which is created by splitting a string.

$tempStyleArray = preg_split( "/[:;]+/", "width: 569px; height: 26.456692913px; margin: 0px; border: 2px solid black;" );

Produces:

array (
  0 => 'width',
  1 => ' 569px',
  2 => ' height',
  3 => ' 26.456692913px',
  4 => ' margin',
  5 => ' 0px',
  6 => ' border',
  7 => ' 2px solid black',
  8 => '',
)

I have to get index/key of the element height from this array. I tried below codes but nothing seems to be working for me.

foreach($tempStyleArray as  $value)
{
   if($value == "height") // not satisfying this condition
   {
     echo $value;
     echo '</br>';
     $key = $i;
   }
} 

in above solution it not satisfying the condition ever :(

$key = array_search('height', $tempStyleArray); // this one not returning anything

Help me to solve this? Is there any problem with my array format?


Solution

  • Try this -

    $tempStyleArray = array_map('trim', preg_split( "/[:;]+/", "width: 569px; height: 26.456692913px; margin: 0px; border: 2px solid black;" ));
    var_dump($tempStyleArray);
    $key = array_search('height', $tempStyleArray);
    echo $key;
    

    It was happening because there was space with the values in array. So needed to be trimmed. After splitting the string every value will be passed through the trim() so that the white spaces are removed.