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

时间:2013-04-19 06:02:52

标签: php regex preg-match-all

我的代码如下:

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

我需要REGEX,$matches只返回两个“this”条目,不带引号。

6 个答案:

答案 0 :(得分:6)

我认为以下应该有效:

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

<强>输出:

Array
(
    [0] => this
    [1] => this
)

答案 1 :(得分:0)

preg_match_all('/"(.*?)".*?\'(.*?)\'/', "I need \"this\" and 'this'", $matches);

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

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

答案 2 :(得分:0)

preg_match_all("/(this).*?(this)/", "I need \"this\" and 'this'", $matches)

或者如果您希望引号之间的文字

preg_match_all("/\"([^\"]*?)\".*?'([^']*?)'/", "I need \"this\" and 'this'", $matches)

答案 3 :(得分:0)

这是一个解决方案:

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

它要求开始和结束报价相同,并且两者之间没有引号。您想要的结果将进入第二个捕获组。

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

答案 4 :(得分: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);

所以,让它也在答案中。

答案 5 :(得分: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