问题
I have code like:
preg_match_all(UNKNOWN, "I need \"this\" and 'this'", $matches)
I need the REGEX that would have the $matches
return just two entries of “this” without quotes.
回答1:
I think following should work:
$str = 'I need "this" and \'this\'';
if (preg_match_all('~(["\'])([^"\']+)\1~', $str, $arr))
print_r($arr[2]);
OUTPUT:
Array
(
[0] => this
[1] => this
)
回答2:
preg_match_all('/"(.*?)".*?\'(.*?)\'/', "I need \"this\" and 'this'", $matches);
But note that the order of quoted strings matter here, so this one will capture ONLY if both quoted strings (single and double) are there AND they are in this order (double - first, single - second).
In order to capture each of them individually, I'd launch preg_match twice with every type of quotes.
回答3:
preg_match_all("/(this).*?(this)/", "I need \"this\" and 'this'", $matches)
or if you want text between quotes
preg_match_all("/\"([^\"]*?)\".*?'([^']*?)'/", "I need \"this\" and 'this'", $matches)
回答4:
You can downvote this answer as much as you want, but in some case you can do:
$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);
So let it be in answers too.
回答5:
Here is one solution:
preg_match_all('/(["\'])([^"\']+)\1/', "I need "this" and 'this'", $matches)
It requires that the opening and closing quote be the same, and that there are no quotes in between. The results you want will go into the second capture group.
To make the regex as reliable as possible, restrict what it matches as much as possible. If the this portion of the regex can contain only letters, use something like [a-z]+
(possibly with case insensitivity) instead.
回答6:
If you want to allow optional text before, between and after the any amount of strings in quotes AND you you want the quotes to be in any order this will work:
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"
This will match all of the following:
Some "text in double quote" and more in "double quotes" here.
"Double quoted text" and 'single quoted text'.
"Two" "Doubles"
'Two' 'singles'
You can see it in action here on Regex101: https://regex101.com/r/XAsewv/2
来源:https://stackoverflow.com/questions/16098223/regex-to-get-content-between-single-and-double-quotes-php