将字符串提取到短代码中
Extract a string into a shortcode
假设我有以下字符串 $shortcode:
content="my temp content" color="blue"
我想像这样转换成一个数组:
array("content"=>"my temp content", "color"=>"blue")
我如何使用爆炸来做到这一点?或者,我需要某种正则表达式吗?
如果我要使用
explode(" ", $shortcode)
它将创建一个元素数组,包括属性中的内容;如果我使用
也是如此
explode("=", $shortcode)
最好的方法是什么?
这有效吗?它基于我在之前的评论中链接的 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);
?>
也许正则表达式不是最好的选择,但你可以试试:
$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
索引是否存在是个好方法。
正则表达式是一种实现方式:
$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);
您可以使用正则表达式,如下所示。我试图使正则表达式保持简单。
<?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);
?>
假设我有以下字符串 $shortcode:
content="my temp content" color="blue"
我想像这样转换成一个数组:
array("content"=>"my temp content", "color"=>"blue")
我如何使用爆炸来做到这一点?或者,我需要某种正则表达式吗? 如果我要使用
explode(" ", $shortcode)
它将创建一个元素数组,包括属性中的内容;如果我使用
也是如此explode("=", $shortcode)
最好的方法是什么?
这有效吗?它基于我在之前的评论中链接的 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);
?>
也许正则表达式不是最好的选择,但你可以试试:
$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
索引是否存在是个好方法。
正则表达式是一种实现方式:
$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);
您可以使用正则表达式,如下所示。我试图使正则表达式保持简单。
<?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);
?>