Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to only match specific characters preceded by a space or nothing (start of line)

Tags:

regex

php

Consider the following tweets:

RT @username This is my tweet
Check this! RT @username This is my tweet
I have PART 2 downloaded

In a preg_replace() call, I am using regex to replace the RT (common retweet syntax) with {RT}. It almost works, however, it also matches RT in PART in the last tweet:

  • I have PART 2 downloaded becomes I have PA{RT} 2 downloaded

I want the regex to only allow nothing (beginning of string) or a space (U+0020) in front of RT.

The current preg_replace() call:

echo preg_replace("(\RT(?=\s)/", '{RT}', $tweet);
like image 934
Pr0no Avatar asked Feb 15 '12 16:02

Pr0no


1 Answers

Use \b for word boundary matching. \bRT\b

like image 92
DVK Avatar answered Oct 05 '22 08:10

DVK