2015-10-16 37 views
2

假设我有以下字符串$简码:提取字符串转换成简码

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

我想转换成一个数组,像这样:

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

我怎么可以这样使用爆炸做?或者,我需要某种正则表达式吗? 如果我使用

explode(" ", $shortcode) 

它会创建元素的数组,包括什么是属性附加伤害里面;如果我使用相同的方式

explode("=", $shortcode) 

什么是最好的方法?

+0

您可以使用类的SimpleXMLElement提取属性:http://stackoverflow.com/a/11440047/3647441 –

+0

不过,我不希望将其转换为XML格式。这只是一个简单的字符串。 – tester2001

回答

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

也许正则表达式是不是最好的选择,但你可以尝试:

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

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

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

这是很好的方法来检查,如果在将其分配给$shortcode数组之前,所有$matches索引都存在。

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