sanchitkhanna26
sanchitkhanna26

Reputation: 2233

Regular expression to match a white space character before the actual pattern - PHP

I have this string -: @Harry @Harry are great twins with @Harry

I would want to match @Harry in the above string. But on one condition -:

@Harry should be preceeded by either nothing or a white space character only, same goes for succession too.

So here 3 matches must be found. Currently i am doing this, but in vain -: (\s|^$)\@Harry(\s|^$).

Upvotes: 2

Views: 147

Answers (1)

Loamhoof
Loamhoof

Reputation: 8293

^$ means an empty string.
[\s means more than a whitespace (source) so you should just use a whitespace :)] <= Unnecessary

So, without taking the whitespace as part of the match:

"/(?<=^|\s)@Harry(?=\s|$)/"

Edit:
Source for the lookarounds.
Also, if you want to match the whitespaces, remove those lookarounds.

Upvotes: 3

Related Questions