-6ren">
gpt4 book ai didi

php - PHP字符串控制台参数数组

转载 作者:IT王子 更新时间:2023-10-29 00:11:53 24 4
gpt4 key购买 nike

我想知道如何将给定的字符串转换为指定的数组:

字符串

all ("hi there \(option\)", (this, that), other) another

想要的结果(数组)
[0] => all,
[1] => Array(
[0] => "hi there \(option\)",
[1] => Array(
[0] => this,
[1] => that
),
[2] => other
),
[2] => another

这用于我在PHP上制作的一种控制台。
我尝试使用 preg_match_all,但是,我不知道如何在括号内找到括号以“在数组内创建数组”。

编辑

示例中未指定的所有其他字符都应视为 String

编辑2

我忘了提到括号内的所有参数都应由 space字符检测到。

最佳答案

毫无疑问,如果您要构建语法树,则应该编写解析器。但是,如果您只需要解析此样本输入regex,它仍然可能是一种工具:

<?php
$str = 'all, ("hi there", (these, that) , other), another';

$str = preg_replace('/\, /', ',', $str); //get rid off extra spaces
/*
* get rid off undefined constants with surrounding them with quotes
*/
$str = preg_replace('/(\w+),/', '\'$1\',', $str);
$str = preg_replace('/(\w+)\)/', '\'$1\')', $str);
$str = preg_replace('/,(\w+)/', ',\'$1\'', $str);

$str = str_replace('(', 'array(', $str);

$str = 'array('.$str.');';

echo '<pre>';
eval('$res = '.$str); //eval is evil.
print_r($res); //print the result

Demo

注意:如果输入格式不正确,则regex肯定会失败。我只是在需要快速脚本的情况下编写此解决方案。编写词法分析器和解析器是耗时的工作,需要大量研究。

关于php - PHP字符串控制台参数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14684764/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com