【问题标题】:preg_match_all: Match custom tagspreg_match_all:匹配自定义标签
【发布时间】:2012-12-06 11:45:30
【问题描述】:

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

Lorem ipsum dolor sit amet (图片:tiger.jpg 宽度:120 高度:200 标题:这张照片显示的是一只老虎) sed diam nonumy eirmod tempor 个人

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

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

(对我而言)棘手的部分是“值”可以包含所有内容,只要它不包含 (\w+)\: 之类的内容 - 因为这是不同标签的开始。下面的 sn-p 代表了我到目前为止所拥有的东西——到目前为止,找到括号内容是可行的,但是将括号内容分成单个标签实际上并不奏效。我使用(\w+) 将值作为占位符进行匹配——这与“tiger.jpg”或“This picture shows a tiger”或其他内容不匹配。我希望你明白我的意思! ;)

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

    }

}

?>

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

【问题讨论】:

  • 你不能使用模板库而不是从头开始吗?
  • 我当然可以,但我更愿意自己做,因为模板库将完全过度杀伤那些简单的事情并不真正需要的功能! ;)
  • 周围有一些相当轻量级的模板库。请记住,这类事情的最大问题之一是安全性。滚动您自己的模板系统很可能会引入 XSS 漏洞。

标签: php preg-match-all


【解决方案1】:
<?

$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',
)
*/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-25
    • 2015-05-21
    • 2018-06-10
    • 1970-01-01
    相关资源
    最近更新 更多