Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP regexp for "start of string or pattern" [duplicate]

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.

like image 219
frankieandshadow Avatar asked Jan 14 '23 10:01

frankieandshadow


1 Answers

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/
like image 78
Jon Avatar answered Jan 22 '23 20:01

Jon