php - Help with regexp

325

I have a tag like this

[tag id="4554" align="center"]

How can i get the tag as a key in an array and then all the arguments are dynamic and inserted in the array as key => value like

Array (
    [tag] => Array
        (
            [id] => 4554
            [align] => "center"
        )

)
569

Answer

Solution:

$string = '[tag id="4554" align="center"]';

preg_match_all('/\[tag id="(?P<id>[^"]+)" align="(?P<align>[^"]+)"\]/', $string, $matches, PREG_SET_ORDER);

foreach($matches as $match) {
    $tag = array(
        'tag' => array(
            'id' => $match['id'],
            'align' => $match['align'],
        ),
    );  
    print_r($tag);
}

Try it here: http://ideone.com/72AxJ

405

Answer

Solution:

I generally favor algorithms to regular expressions:

$str = '[tag id="4554" align="center"]';

$arr = explode(" ",trim($str,'[]'));

$mainkey = array_shift($arr);

$temp = array();
foreach($arr as $part)
{
    $parts = explode("=",$part);
    $temp[$parts[0]] = trim($parts[1], '"');
}

$arr2[$mainkey] = $temp;

print_r($arr2);

outputs:

Array
(
    [tag] => Array
        (
            [id] => 4554
            [align] => center
        )

)

People are also looking for solutions to the problem: forms - php drops file type error for file size

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.