Is there a way (other than by doing two separate pattern matches) to use preg_match in PHP to test for either the beginning of the string or a pattern? More specifically I often find myself wanting to test that I have a matching pattern which is not preceded by something, as in
preg_match('/[^x]y/', $test)
(that is, match y if it is not preceded by x), but to also match y if it occurs at the start of $test (when it also isn't preceded by x, but isn't preceded by any character, so the [^x] construct won't work as it always requires a character to match it.
There's a similar problem at the end of strings, to determine whether a pattern occurs that is not followed by some other pattern.
You can simply use standard alternation syntax:
/(^|[^x])y/
This will match a y
that is preceded either by the start of the input or by any character other than x
.
Of course in this specific instance, where the alternative to the ^
anchor is so simple, you can also very well use negative lookbehind:
/(?<!x)y/
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