tester2001
tester2001

Reputation: 1073

Extract a string into a shortcode

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?

Upvotes: 2

Views: 359

Answers (4)

BudwiseЯ
BudwiseЯ

Reputation: 1826

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);

Upvotes: 1

Subash
Subash

Reputation: 7266

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

Upvotes: 0

marian0
marian0

Reputation: 3337

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.

Upvotes: 1

mario.van.zadel
mario.van.zadel

Reputation: 2949

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);

?>

Upvotes: 2

Related Questions