I want to capture a pattern upto but not including the first instance of an optional other pattern with preg_match, eg:
ABCDEFGwTW$% | capture ABCD
@Q%HG@H%hg afdgwsa g weg#D DEFG | capture @Q%HG@H%hg afdgwsa g weg#D D
@Q%HDEFG@H%hg afdgwsa g weg#D DEFG | capture @Q%HD
So in the above case anything before the first instance of the string EFG
is captured. also, if the EFG
string is not present then I want to capture the whole string.
I would have thought that the following would work, but no such luck:
$pattern = '/(.*)(?:EFG)?/';
preg_match($pattern, 'Q$TQ@#%GEFGw35hqb', $matches);
print_r($matches);
//should give: 'Q$TQ@#%G'
How do you ignore something in regex? To match any character except a list of excluded characters, put the excluded charaters between [^ and ] . The caret ^ must immediately follow the [ or else it stands for just itself.
The position anchors ^ and $ match the beginning and the ending of the input string, respectively. That is, this regex shall match the entire input string, instead of a part of the input string (substring). \w+ matches 1 or more word characters (same as [a-zA-Z0-9_]+ ).
The order of the characters inside a character class does not matter. The results are identical. You can use a hyphen inside a character class to specify a range of characters. [0-9] matches a single digit between 0 and 9.
You can use
'/(.*?)(?=EFG|$)/'
Try this: (.*?)(?:EFG|$)
This will match any character (as few as possible) until it finds EFG.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With