什么正则表达式解析双引号字符串后跟变量名称?

时间:2015-02-24 17:47:30

标签: php regex handlebars.js

我正在为车把做一个帮手,想要解析这样的事情:

"hello \"great\" friend" var1 var2

我现在使用的表达式适用于字符串中没有双引号的内容:

(?<=")[^"]*(?=")|(\w+)

感谢您的帮助!

句柄使用情况为{{#gettext "Hello \"friend\" %s %s" var1 var2}},其中#gettext是我的自定义帮助程序,它使用从第一个"}}之前的字符串

澄清

我不希望\在渲染时出现。 期望输出应为:

// Array of matches via preg_match_all
Hello "great" friend
var1
var2

3 个答案:

答案 0 :(得分:1)

我做了不同的解决方案。

它更灵活一点:

/"((?:\\"|[^"])+)"| (\w+)/g

这匹配引号内部或外部的所有内容与之前的空格。

您可以查看this链接,了解相关信息。

答案 1 :(得分:0)

您可以使用:

$str = '"hello \"great\" friend" var1 var2';
$re = '/"(.+?)(?<!\\\\)"\h+(\w+)\h+(\w+)/';
preg_match($re, $str, $matches);
$matches[1] = stripslashes($matches[1]);
array_shift($matches);
print_r($matches);

<强>输出:

Array
(
    [0] => hello "great" friend
    [1] => var1
    [2] => var2
)

RegEx Demo

答案 2 :(得分:0)

那就像......

(^".*")|([ ]+([^ "]+))

<强>解释

贪婪地匹配以"结尾的最长前缀。由于此部分锚定到测试字符串的开头,因此正则表达式的这部分将永远不会再匹配。相反,第二部分获取所有以空格分隔的变量名称。

RegexDemo here

嵌入代码

重新格式化输出。 正则表达式和代码使用多对转义引号和任意数量的变量。

function postprocess ( &$item, $key ) {
    if ($key == 0) {
        $item = str_replace('\\"', '"', substr($item, 1, strlen($item)-2));
    }
    else {
        $item = substr($item, 1);
    }
}

$str = '"hello \"great\" friend of \"mine\"" var1 var2 var3 var4';
$re = '/(^"(.*)")|([ ]+([^ "]+))/';
preg_match_all($re, $str, $matches);
$matches = $matches[0];  # Array of complete matches
array_walk ($matches, 'postprocess');
print_r($matches);

此代码已在writecodeonline.com上进行了测试。

<强>输出

Array
(
    [0] => hello "great" friend of mine
    [1] => var1
    [2] => var2
    [3] => var3
    [4] => var4
)
相关问题