1

每个人。我有一个问题,我无法解决。

图案:\'(.*?)\'

源字符串:'abc', 'def', 'gh\'', 'ui'

我需要[abc],,,,[def]_[gh\'][ui]

但我得到[abc], [def], [gh\],[, ]等等。

可能吗?提前致谢

4

4 回答 4

1

PHP 代码:使用负面的后视

$s = "'abc', 'def', 'ghf\\\\', 'jkl\'f'";
echo "$s\n";
if (preg_match_all("~'.*?(?<!(?:(?<!\\\\)\\\\))'~", $s, $arr))
   var_dump($arr[0]);

输出:

array(4) {
  [0]=>
  string(5) "'abc'"
  [1]=>
  string(5) "'def'"
  [2]=>
  string(7) "'ghf\\'"
  [3]=>
  string(8) "'jkl\'f'"
}

现场演示:http: //ideone.com/y80Gas

于 2013-10-07T17:10:18.853 回答
1

是的,这些匹配是可能的。

但是,如果您要询问是否可以获取引号内的内容,这里最简单的方法是用逗号分隔(最好通过 CSV 解析器)并修剪任何尾随空格。

否则,您可以尝试以下操作:

\'((?:\\\'|[^\'])+)\'

这将匹配任何\'一个或非引号字符,但会失败\\'...

对于这种情况,您可能使用的更长、更慢的正则表达式是:

\'((?:(?<!\\)(?:\\\\)*\\\'|[^\'])+)\'

在 PHP 中:

preg_match_all('/\'((?:(?<!\\)\\\'|[^\'])+)\'/', $text, $match);

或者,如果您使用双引号:

preg_match_all("/'((?:(?<!\\\)\\\'|[^'])+)'/", $text, $match);

(?<!\\)不知道为什么应该正常工作时(我真的是指一个文字反斜杠)有错误。如果模式更改为(?<!\\\\).

ideone演示

编辑:找到一个更简单、更好、更快的正则表达式:

preg_match_all("/'((?:[^'\\]|\\.)+)'/", $text, $match);
于 2013-10-07T16:53:26.657 回答
0
<?php

    // string to extract data from 
    $string  = "'abc', 'def', 'gh\'', 'ui'";

    // make the string into an array with a comma as the delimiter 
    $strings = explode(",", $string);

    # OPTION 1: keep the '

        // or, if you want to keep that escaped single quote
        $replacee = ["'", " "];
        $strings  = str_replace($replacee, "", $strings);
        $strings  = str_replace("\\", "\'", $strings);


    # OPTION 2: remove the ' /// uncomment tripple slash

        // replace the single quotes, spaces, and the backslash 
        /// $replacee = ["'", "\\", " "];

        // do the replacement, the $replacee with an empty string
        /// $strings = str_replace($replacee, "", $strings);


    var_dump($strings);

?>
于 2013-10-07T18:04:25.607 回答
-1

相反,您应该使用str_getcsv

str_getcsv("'abc', 'def', 'gh\'', 'ui'", ",", "'");
于 2013-10-07T16:53:18.537 回答