I need to make a regex that recognizes everything except text between quotes. Here is an example:
my_var == "Hello world!"
I want to get my_var
but not Hello world!
.
I tried (?<!\")([A-Za-z0-9]+)
but it didn't work.
I need to make a regex that recognizes everything except text between quotes. Here is an example:
my_var == "Hello world!"
I want to get my_var
but not Hello world!
.
I tried (?<!\")([A-Za-z0-9]+)
but it didn't work.
If you would of took the time to google
or search stackoverflow
, you would find answers to this question that have already been answered by not only me, but many other users out there.
@Pappa's
answer using a negative lookbehind
will only match a simple test case and not everything in a string that is not enclosed by quotes. I would suffice for a negative lookahead
in this case, if you're wanting to match all word characters in any given data.
/[\w.-]+(?![^"]*"(?:(?:[^"]*"){2})*[^"]*$)/
See live demo
Example:
<?php
$text = <<<T
my_var == "Hello world!" foo /(^*#&^$
"hello" foobar "hello" FOO "hello" baz
Hi foo, I said "hello" $&@^$(@$)@$&*@(*$&
T;
preg_match_all('/[\w.-]+(?![^"]*"(?:(?:[^"]*"){2})*[^"]*$)/', $text, $matches);
print_r($matches);
Output
Array
(
[0] => Array
(
[0] => my_var
[1] => foo
[2] => foobar
[3] => FOO
[4] => baz
[5] => Hi
[6] => foo
[7] => I
[8] => said
)
)
You have an accepted answer but I am still submitting once since I believe this answer is better in capturing more edge cases:
$s = 'my_var == "Hello world!" foo';
if (preg_match_all('/[\w.-]+(?=(?:(?:[^"]*"){2})*[^"]*$)/', $s, $arr))
print_r($arr[0]);
OUTPUT:
Array
(
[0] => my_var
[1] => foo
)
This works by using a lookahead to make sure there are even # of double quotes are followed (requires balanced double quotes and no escaping).
As much as I'll regret getting downvoted for answering this, I was intrigued, so did it anyway.
(?<![" a-zA-Z])([A-Za-z0-9\-_\.]+)