nn3112337
nn3112337

Reputation: 599

RegEx: Only start if nothing or space is before string

Im bad at regex and I got stuck at this, I found a few links and sadly it didn't work.

$str = preg_replace("/@([a-zA-Z0-9]+)/", '<span class="label label-default">$1</span>', $str);
$str = preg_replace("~/r(.*?)(?:<br>|$)~uis", '<font color="red">$1</font><br>', $str);

so currently both of these match the correct thing, they both do what I want.
For clarification: the first line does the next word to @ in a special css class, and the second line makes the textline after /r red. BUT the @ works also in things like [email protected] and /r works in things like .com/r/test, both is not what I want.
I already tried this, but its not working :/

"/(^|[ ])@([a-zA-Z0-9]+)/"
"/\b@([a-zA-Z0-9]+)/"

Upvotes: 2

Views: 504

Answers (1)

anubhava
anubhava

Reputation: 785196

You can use this lookbehind based regex:

$str = preg_replace('/(?<=^| )@([a-zA-Z0-9]+)/m', '<span class="label label-default">$1</span>', $str);
$str = preg_replace('~(?<=^| )/r(.*?)(?:<br>|$)~uims', '<font color="red">$1</font><br>', $str);

Here (?<=^| ) is a lookbehid which means match your regex if it is preceded by space or is at line start.

Upvotes: 2

Related Questions