Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/266.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 将字符串提取到短代码中_Php_Regex_Shortcode - Fatal编程技术网

Php 将字符串提取到短代码中

Php 将字符串提取到短代码中,php,regex,shortcode,Php,Regex,Shortcode,假设我有以下字符串$shortcode: content="my temp content" color="blue" 我想转换成这样的数组: array("content"=>"my temp content", "color"=>"blue") 如何使用explode执行此操作?或者,我需要某种正则表达式吗? 如果我使用 explode(" ", $shortcode) explode("=", $shortcode) 它将创建一系列元素,包括心房内的内容;如果我使用 e

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

content="my temp content" color="blue"
我想转换成这样的数组:

array("content"=>"my temp content", "color"=>"blue")
如何使用explode执行此操作?或者,我需要某种正则表达式吗? 如果我使用

explode(" ", $shortcode)
explode("=", $shortcode)
它将创建一系列元素,包括心房内的内容;如果我使用

explode(" ", $shortcode)
explode("=", $shortcode)

最好的方法是什么?

这样行吗?这是基于我在之前的评论中链接的:

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

?>
test[0]->attributes()作为$key=>$val){
$attraray[(字符串)$key]=(字符串)$val;
}
打印(数组);
?>

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

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

您可以使用regex进行如下操作。我试图让正则表达式保持简单

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


您可以使用SimpleXmlElement类来提取属性:但是,我不想将其转换为xml格式。它只是一个简单的字符串。