Reputation: 10422
I have a SQL string I'm trying to match using PHP preg_match_all
and I need to extract out the matches. It looks like this:
A BUNCH OF MEANINGLESS SQL And (Condition1 = 'thisvalue*' Or Condition1 = '8504577' Or Condition1 = 'somethingelse123*') And MORE MEANINGLESS SQL
I want to grab all those Condition1 = X
parts and use them in a different area, but ONLY if they are in the larger sub-condition in parentheses and are connected by Or
s.
My regex looks like this (https://www.regex101.com/r/gepdq9/3):
/(\((Condition1 = '[\dA-Za-z]+\*?'(\sOr\s)?)+\))/
It matches the larger sub-condition correctly, but for some reason the matches[3]
item, which I think should be capturing all the thisvalue*
, 8504577
and somethingelse123*
values, is only capturing the last one.
How can I capture all of these matches?
Upvotes: 0
Views: 132
Reputation: 146
here is a sample code that will work for your example:
$a="A BUNCH OF MEANINGLESS SQL And (Condition1 = 'thisvalue*' Or Condition1 = '8504577' Or Condition1 = 'somethingelse123') And MORE MEANINGLESS SQL";
if (preg_match('/\((Condition1.*( Or )?)\) /',$a,$m)){
print $m[1]; /* Condition1 = 'thisvalue*' Or Condition1 = '8504577' Or Condition1 = 'somethingelse123' */
}
it looking for the "(Condition1" that follow with " Or " 1 or 0 times. the 0 times is for that last one that don't have any more " Or " after it. follow by a ")" to capture them all. Next, because you are in PHP, if you want to remove all the " Or " and have each of the condition in its own var, do something like
$arr=explode(' Or ',$m[1]); /* "Condition1='thisvalue*'", "Condition1 = '8504577'",... */
If you want to break it all in regEx and see just the conditions values, you can try this:
$a="A BUNCH OF MEANINGLESS SQL And (Condition1 = 'thisvalue*' Or Condition1 = '8504577' Or Condition1 = 'somethingelse123') And MORE MEANINGLESS SQL";
if (preg_match_all("/Condition1 = '([^']+)'( Or )?/",$a,$m)){
print_r($m[1]); /* [0] => thisvalue* [1] => 8504577 [2] => somethingelse123 */
}
Upvotes: 1