求组一个正则的问题,希望各位 dalao 赐教

2016-07-20 00:15:35 +08:00
 xiaome

刚接触正则,想实现一个类似 UBB 的“简码”功能,不知道思路对不对。

直接贴代码吧

function shortcode_parse($text) {
$atts = array();
$pattern = '/([\w-]+)\s*=\s*"([^"]*)"(?:\s|$)|([\w-]+)\s*=\s*\'([^\']*)\'(?:\s|$)|([\w-]+)\s*=\s*([^\s\'"]+)(?:\s|$)|"([^"]*)"(?:\s|$)|(\S+)(?:\s|$)/';
if ( preg_match_all($pattern, $text, $match, PREG_SET_ORDER) ) {
    foreach ($match as $value ) {
        if (!empty($value [1]))
            $atts[strtolower($value [1])] = $value [2];
        elseif (!empty($value [3]))
            $atts[strtolower($value [3])] = $value [4];
        elseif (!empty($value [5]))
            $atts[strtolower($value [5])] = $value [6];
        elseif (isset($value [7]) && strlen($value [7]))
            $atts[] = $value [7];
        elseif (isset($value [8]))
            $atts[] = $value [8];
    }
}
return $atts;
}   

$atts = '[test id1="xxx" id2="xxx" id3="xxx" id4="xxx"]';
$attx = shortcode_parse($atts);

print_r($attx);

现在实现出来是这样的:

Array
(
    [0] => [test
    [id1] => xxx
    [id2] => xxx
    [id3] => xxx
    [1] => id4="xxx"]
)

希望实现下面这样的效果:

Array
(
    [0] => [
    [1] => test
    [id1] => xxx
    [id2] => xxx
    [id3] => xxx
    [id4] => xxx
    [2] => ]
)

希望各位 dalao 可以为小弟解惑,谢谢。

2266 次点击
所在节点    PHP
4 条回复
stormouse
2016-07-20 20:33:46 +08:00
额…能稍微说的再清楚一点吗,下面那个效果是什么意思= =
hanmiao
2016-07-20 21:11:12 +08:00
@xiaome
xiaome
2016-07-20 23:42:55 +08:00
@stormouse 追加了信息,大概描述出来了。
kair
2016-07-22 15:01:12 +08:00
(\[)(\w*) id\d=\"(.*)\"(\])
是不是这种效果?

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/293604

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX