在单词前添加 +,将引号之间的所有内容视为一个单词

Add + before word, see all between quotes as one word

我有一个问题。我需要在每个单词前添加一个 + 并将引号之间的所有内容视为一个单词。

有这个代码

preg_replace("/\w+/", '+[=10=]', $string);

这导致了这个

+test +demo "+bla +bla2

但我需要 +test +demo +"bla bla2"

有人可以帮助我吗:) 如果已经有一个+,是否可以不添加?所以你不会得到 ++test

谢谢!

我无法对此进行测试,但你可以尝试一下并告诉我结果如何吗?

首先是正则表达式:从前面可以有或没有“+”的一系列字母中选择一个,或者选择一个引号,后跟任意数量的字母或 spaces,其中前面可以有一个“+”,后跟一个引号。

我希望这符合您的所有示例。

然后我们获取字符串中正则表达式的所有匹配项,将它们存储在数组变量“$matches”中。然后我们遍历这个数组测试是否有一个 '+' 作为第一个字符。如果有,什么也不做,否则加一个。

然后我们将数组内爆成一个字符串,用 space.

分隔元素

注意:我相信 $matches 在作为参数提供给 preg_match 时创建。

$regex = '/[((\+)?[a-zA-z]+)(\"(\+)?[a-zA-Z ]+\")]/';

preg_match($regex, $string, $matches);

foreach($matches as $match)
{
    if(substr($match, 0, 1) != "+") $match = "+" + $match;
}

$result = implode($matches, " ");

也许你可以使用这个正则表达式:

$string = '+test demo between "double quotes" and between \'single quotes\' test';
$result = preg_replace('/\b(?<!\+)\w+|["|\'].+?["|\']/', '+[=10=]', $string);
var_dump($result);

// 这将导致:

string '+test +demo +between +"double quotes" +and +between +'single quotes' +test' (length=74)

我用 'negative lookbehind' 来检查“+”。 Regex lookahead, lookbehind and atomic groups