我正在寻找一种简单的方法,将用引号("
或'
)包围的文本解析为一个字符串,在该字符串中可以使用相同的引号字符(用反斜杠'
转义)。所以PHP在解析字符串时在内部做的事情基本上是一样的。Python有literal_eval
(感谢@georg指出这一点)。
示例
输入
"This is a '"cool'" string"
输出
This is a "cool" string
使用eval
是可行的,但我希望避免使用它
$str = '"This is a ''"cool''" string"';
$a = eval("return $str;");
var_dump($a);
// Output: string(23) "This is a "cool" string"
有什么内置的东西吗?
编辑
哇,我真的认为"解析字符串"并解释"所以PHP在解析字符串时在内部做的基本上相同的事情"将是一个明显的请求:D
想想一个更高级的例子:
输入
"This is a '"cool'" string that contains one backslash '' or maybe two in a row ''''"
输出
This is a "cool" string that contains one backslash ' or maybe two in a row ''
相应的PHP代码是:
$input = '"This is a ''"cool''" string that contains one backslash '''' or maybe two in a row ''''''''"';
$output = parse_quoted_string($str);
var_dump($output);
// string(78) "This is a "cool" string that contains one backslash ' or maybe two in a row ''"
我正在为parse_quoted_string()
寻找合适的功能。
输入字符串是JSON-只需使用json_decode
。
演示