0

我目前正在玩一些正则表达式,并希望在我的网站上为文本实现某种自定义标签。例如,如果我想将图片实现为文本,我使用下面的括号标签来做到这一点......</p>

Lorem ipsum dolor sit amet (图片:tiger.jpg 宽度:120 高度:200 标题:此图为老虎) sed diam nonumy eirmod tempor invidunt

现在我希望我的 PHP 脚本 1. 找到这些括号标签和 2. 读取这个括号中的单个标签,所以我得到某种数组,比如......</p>

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

(对我来说)棘手的部分是“值”可以包含所有内容,只要它不包含类似的东西(\w+)\:- 因为这是不同标签的开始。下面的代码片段代表了我到目前为止所拥有的内容——到目前为止,找到括号内容是可行的,但是将括号内容拆分为单个标签实际上并不奏效。我用于(\w+)匹配值只是作为占位符 - 这不会匹配“tiger.jpg”或“这张图片显示老虎”或其他内容。我希望你明白我的意思!;)

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

    }

}

?>

如果有人可以帮助我解决这个问题,那就太好了!谢谢!:)

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 回答