【问题标题】:PHP explode the string, but treat words in quotes as a single word and ignore bracketsPHP分解字符串,但将引号中的单词视为单个单词并忽略括号
【发布时间】:2017-07-03 21:47:17
【问题描述】:

我正在使用来自2202435 的解决方案。但是当我在字符串中添加括号时,它不会在数组中给出正确的结果。

 $text = 'Lorem ipsum ("dolor sit amet") consectetur "adipiscing \\"elit" dolor';
preg_match_all('/"(?:\\\\.|[^\\\\"])*"|\S+/', $text, $matches);
print_r($matches);

以上代码产生

   Array
(
    [0] => Array
        (
            [0] => Lorem
            [1] => ipsum
            [2] => ("dolor
            [3] => sit
            [4] => amet")
            [5] => consectetur
            [6] => "adipiscing \"elit"
            [7] => dolor
        )

)

但我正在寻找的结果是

    Array
(
    [0] => Array
        (
            [0] => Lorem
            [1] => ipsum
            [2] => (
            [3] => "dolor sit amet"
            [4] => )
            [5] => consectetur
            [6] => "adipiscing \"elit"
            [7] => dolor
        )

)

如果我在 '( ' 和 ' )' 之前包含一个空格,我能够实现上述结果。

请提供正确的正则表达式,使我能够将括号分开(如果可能,请提供解释)。

谢谢。

【问题讨论】:

  • 原因是你使用的正则表达式是为了在匹配中保持独立的"。也许'/"(?:\\\\.|[^\\\\"])*"|[^\s"]+/' 会帮助你。
  • 您确定未转义的双引号在您的输入中始终成对出现吗?
  • @WiktorStribiżew 谢谢,您的解决方案有效。至于输入,是的,双引号总是需要配对,因为它是查询数据库的搜索字符串的一部分。是否可以将单引号中的单词与双引号一起包含为单个单词?

标签: php regex preg-match-all quotes brackets


【解决方案1】:

原因是您使用的正则表达式是为了在匹配中保持独立的"

如果您确定未转义的双引号始终在您的输入中成对出现,请使用

'/"(?:\\\\.|[^\\\\"])*"|[^\s"]+/'
                        ^^^^^^

通过将\S 中的" 转换为负字符类[^\s] 并在其中添加双引号来排除"

要包含单引号子字符串,您可以使用

'~"(?:\\\\.|[^\\\\"])*"|\'(?:\\\\.|[^\\\\\'])*\'|[^\s"\']+~'

查看regex demoPHP demo

$re = '~"(?:\\\\.|[^\\\\"])*"|\'(?:\\\\.|[^\\\\\'])*\'|[^\s"\']+~';
$str = 'Lorem ipsum ("dolor sit amet") consectetur "adipiscing \\"elit" dolor \'something  \\\'here\'';
preg_match_all($re, $str, $matches);
print_r($matches[0]);
// => Array ( [0] => Lorem [1] => ipsum [2] => ( [3] => "dolor sit amet" [4] => )
//   [5] => consectetur [6] => "adipiscing \"elit" [7] => dolor [8] => 'something  \'here' )

【讨论】:

  • 这行得通,但我不确定如何转义字符串 \'apple\\\'s\' ?
  • 逃避是什么意思?在 PHP 代码中用作字符串文字? 'apple\'s' 应定义为 $s = "'apple\\'s'";
  • 我的意思是如果我使用 addlashes("'apple's'");这基本上会返回\'apple\'s\'。由于该值来自发布的变量
  • 是的,it will,那么有什么问题吗?你想说你还需要匹配“狂野”的引号吗?
  • 如果我尝试通过之前的解决方案 ideone.com/PvsKtB 运行它,结果应该是 Array ( [0] => 'apple\'s' )。
猜你喜欢
  • 2011-01-13
  • 2020-05-08
  • 2022-07-29
  • 1970-01-01
  • 2011-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多