将字符串提取为短代码

时间:2015-10-16 06:15:58

标签: php regex shortcode

假设我有以下字符串$ shortcode:

content="my temp content" color="blue"

我想转换成这样的数组:

array("content"=>"my temp content", "color"=>"blue")

我怎样才能使用爆炸?或者,我需要某种正则表达式吗? 如果我要使用

explode(" ", $shortcode)

它会创建一个元素数组,包括属性中的内容;如果我使用

,情况也是如此
explode("=", $shortcode)

最好的方法是什么?

4 个答案:

答案 0 :(得分:2)

这有用吗?它基于我之前评论中链接的example

<?php
    $str = 'content="my temp content" color="blue"';
    $xml = '<xml><test '.$str.' /></xml>';
    $x = new SimpleXMLElement($xml);

    $attrArray = array();

    // Convert attributes to an array
    foreach($x->test[0]->attributes() as $key => $val){
        $attrArray[(string)$key] = (string)$val;
    }

    print_r($attrArray);

?>

答案 1 :(得分:1)

也许正则表达式不是最佳选择,但您可以尝试:

$str = 'content="my temp content" color="blue"';

$matches = array();
preg_match('/(.*?)="(.*?)" (.*?)="(.*?)"/', $str, $matches);

$shortcode = array($matches[1] => $matches[2], $matches[3] => $matches[4]);

在将它们分配给$matches数组之前检查是否存在所有$shortcode索引是一种很好的方法。

答案 2 :(得分:1)

正则表达式是一种方法:

$str = 'content="my temp content" color="blue"';

preg_match_all("/(\s*?)(.*)=\"(.*)\"/U", $str, $out);

foreach ($out[2] as $key => $content) {
    $arr[$content] = $out[3][$key];
}

print_r($arr);

答案 3 :(得分:0)

您可以使用正则表达式执行此操作,如下所示。我试图保持正则表达式简单。

<?php
    $str = 'content="my temp content" color="blue"';
    $pattern = '/content="(.*)" color="(.*)"/';
    preg_match_all($pattern, $str, $matches);
    $result = ['content' => $matches[1], 'color' => $matches[2]];
    var_dump($result);
?>