0

I'm currently playing around a bit with regular expressions and want to implement some kind of custom tags for texts on a site of mine. For example, if I want to implement a picture into a text, I use the following bracket-tag to do so…</p>

Lorem ipsum dolor sit amet (image: tiger.jpg width: 120 height: 200 title: This picture shows a tiger) sed diam nonumy eirmod tempor invidunt

Now I want my PHP-script to 1. find these bracket-tags and 2. read the single tags in this brackets, so I get some kind of an array like…</p>

$attributes = array(
    'image' => 'tiger.jpg',
    'width' => '150',
    'height' => '250',
    'title' => 'This picture shows a tiger',
);

The (for me) tricky part about this is that the "values" can contain everything as long it doesn't contain something like (\w+)\: – because this is the start of an different tag. The following snippet represents what I have so far – finding the brackets-things works so far, but splitting the bracket-contents into the single tags doesn't really work. I used (\w+) for matching the value just as a placeholder – this would not match "tiger.jpg" or "This picture shows a tiger" or something else. I hope you understand what I mean! ;)

<?php

$text = 'Lorem ipsum dolor sit amet (image: tiger.jpg width: 150 height: 250 title: This picture shows a tiger) sed diam nonumy eirmod tempor invidunt';

// find all tag-groups in brackets
preg_match_all('/\((.*)\)/s', $text, $matches);

// found tags?
if(!empty($matches[0])) {

    // loop through the tags
    foreach($matches[0] as $key => $val) {

        $search = $matches[0][$key]; // this will be replaced later
        $cache = $matches[1][$key]; // this is the tag without brackets

        preg_match_all('/(\w+)\: (\w+)/s', $cache, $list); // find tags in the tag-group (i.e. image, width, …)

        echo '<pre>'.print_r($list, true).'</pre>';

    }

}

?>

Would be great if somebody could help me out of this! Thanks! :)

4

1 に答える 1

0
<?

$text = 'Lorem ipsum dolor sit amet (image: tiger.jpg width: 150 height: 250 title: This picture shows a tiger) sed diam nonumy eirmod tempor invidunt';

// find all tag-groups in brackets
preg_match_all('/\(([^\)]+)\)/s', $text, $matches);
$attributes = array();

// found tags?
if ($matches[0]) {
    $m = preg_split('/\s*(\w+)\:\s+/', $matches[1][0], -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
    for ($i = 0; $i < count($m); $i+=2) $attributes[$m[$i]] = $m[$i + 1];
}

var_export($attributes);

/*
array (
  'image' => 'tiger.jpg',
  'width' => '150',
  'height' => '250',
  'title' => 'This picture shows a tiger',
)
*/
于 2012-12-24T18:59:51.840 に答える