2

Suppose I have the following string $shortcode:

content="my temp content" color="blue"

And I want to convert into an array like so:

array("content"=>"my temp content", "color"=>"blue")

How can I do this using explode? Or, would I need some kind of regex? If I were to use

explode(" ", $shortcode)

it would create an array of elements including what is inside the atribute; the same goes if I were to use

explode("=", $shortcode)

What would be the best approach?

Niranjan N Raju
  • 12,047
  • 4
  • 22
  • 41
tester2001
  • 1,053
  • 3
  • 14
  • 24

4 Answers4

2

Is this working? It is based on the example that I've linked in my previous comment:

<?php
    $str = 'content="my temp content" color="blue"';
    $xml = '<xml><test '.$str.' /></xml>';
    $x = new SimpleXMLElement($xml);

    $attrArray = array();

    // Convert attributes to an array
    foreach($x->test[0]->attributes() as $key => $val){
        $attrArray[(string)$key] = (string)$val;
    }

    print_r($attrArray);

?>
Community
  • 1
  • 1
mario.van.zadel
  • 2,919
  • 14
  • 23
1

Maybe regular expression is not the best option, but you can try:

$str = 'content="my temp content" color="blue"';

$matches = array();
preg_match('/(.*?)="(.*?)" (.*?)="(.*?)"/', $str, $matches);

$shortcode = array($matches[1] => $matches[2], $matches[3] => $matches[4]);

It's good approach to check if all of $matches indexes exist before assigning them to $shortcode array.

marian0
  • 3,336
  • 3
  • 27
  • 37
1

Regex is a way to do it:

$str = 'content="my temp content" color="blue"';

preg_match_all("/(\s*?)(.*)=\"(.*)\"/U", $str, $out);

foreach ($out[2] as $key => $content) {
    $arr[$content] = $out[3][$key];
}

print_r($arr);
BudwiseЯ
  • 1,846
  • 2
  • 16
  • 28
0

You could do it using regex as follows. I have tried to keep the regex simple.

<?php
    $str = 'content="my temp content" color="blue"';
    $pattern = '/content="(.*)" color="(.*)"/';
    preg_match_all($pattern, $str, $matches);
    $result = ['content' => $matches[1], 'color' => $matches[2]];
    var_dump($result);
?>
Subash
  • 7,098
  • 7
  • 44
  • 70