2

我有如下代码:

preg_match_all(UNKNOWN, "I need \"this\" and 'this'", $matches)

我需要正则表达式,它只$matches返回两个不带引号的“this”条目。

4

6 回答 6

6

我认为以下应该工作:

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

输出:

Array
(
    [0] => this
    [1] => this
)
于 2013-04-19T06:10:22.070 回答
0

您可以根据需要对这个答案投反对票,但在某些情况下,您可以这样做:

$str = "I need \"this\" and 'this'";
$str = str_replace('\'','"',$str);
$arr = explode('"',$str);
foreach($arr as $key => $value)
    if(!($key&1)) unset($arr[$key]);
print_R($arr);

所以让它也出现在答案中。

于 2013-04-19T06:27:48.473 回答
0
preg_match_all('/"(.*?)".*?\'(.*?)\'/', "I need \"this\" and 'this'", $matches);

但请注意,引用字符串的顺序在这里很重要,因此只有当两个引用字符串(单和双)都存在并且它们按此顺序(双 - 第一,单 - 第二)时,这个才会捕获。

为了单独捕获它们中的每一个,我会使用每种类型的引号启动 preg_match 两次。

于 2013-04-19T06:06:36.717 回答
0
preg_match_all("/(this).*?(this)/", "I need \"this\" and 'this'", $matches)

或者如果你想要引号之间的文字

preg_match_all("/\"([^\"]*?)\".*?'([^']*?)'/", "I need \"this\" and 'this'", $matches)
于 2013-04-19T06:07:17.047 回答
0

这是一种解决方案:

preg_match_all('/(["\'])([^"\']+)\1/', "I need "this" and 'this'", $matches)

它要求开头和结尾的引号相同,并且中间没有引号。您想要的结果将进入第二个捕获组。

为了使正则表达式尽可能可靠,请尽可能限制它匹配的内容。如果正则表达式的部分只能包含字母,请改用类似的东西[a-z]+(可能不区分大小写)。

于 2013-04-19T06:11:19.030 回答
0

如果您想在引号中任意数量的字符串之前、之间和之后允许可选文本,并且您希望引号以任何顺序排列,这将起作用:

preg_match("~^(?:[\s\S]*)?(?:(?:\"([\s\S]+)\")|(?:'([\s\S]+)'))(?:[\s\S]*)?(?:(?:\"([\s\S]+)\")|(?:'([\s\S]+)'))(?:[\s\S]+)?$~", "some \"text in double quotes\" and more 'text to grab' here", $matches);

$matches[1]; // "text in double quotes";
$matches[2]; // "text to grab"

这将匹配以下所有内容:

Some "text in double quote" and more in "double quotes" here.
"Double quoted text" and 'single quoted text'.
"Two" "Doubles"
'Two' 'singles'

您可以在 Regex101 上看到它的实际效果: https ://regex101.com/r/XAsewv/2

于 2017-01-24T17:07:27.697 回答