正则表达式获取单引号和双引号php之间的内容

use*_*938 2 php regex preg-match-all

我的代码如下:

preg_match_all(UNKNOWN, "I need \"this\" and 'this'", $matches)
Run Code Online (Sandbox Code Playgroud)

我需要REGEX $matches只返回两个没有引号的"this"条目.

anu*_*ava 6

我认为以下应该有效:

$str = 'I need "this" and \'this\'';
if (preg_match_all('~(["\'])([^"\']+)\1~', $str, $arr))
   print_r($arr[2]);
Run Code Online (Sandbox Code Playgroud)

OUTPUT:

Array
(
    [0] => this
    [1] => this
)
Run Code Online (Sandbox Code Playgroud)

  • 应该注意的是,这会导致像"不要"这样的问题,因为否定的字符类同时限制了两种情况.这可以通过一个不合理的`(.+?)来解决,一个替换,每个替换为''和```或负前瞻`((?:(?!\ 1).)+)`.我想这种变化将是最干净,最有效的. (2认同)