从代码中提取所有字符串值


Extract all strings values from code

everyone.我有一个问题,我无法解决它。

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

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

我需要[abc][def][gh''][ui]

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

可能吗?提前致谢

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

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

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

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

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

这将匹配''或非引号字符,但会失败于像'''这样的东西......

在这种情况下,

您可以使用更长、更慢的正则表达式是:

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

在 PHP 中:

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

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

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

不知道为什么(?<!'')(我的意思是一个字面反斜杠)应该正常工作时会出现错误。如果模式更改为 (?<!'''') .

IDEe演示

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

preg_match_all("/'((?:[^''']|''.)+)'/", $text, $match);
<?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);
?>

相反,您应该使用str_getcsv

str_getcsv("'abc', 'def', 'gh''', 'ui'", ",", "'");