djderek
djderek

Reputation: 41

Matching specific characters preceded by a space or nothing Regex

Following this post I am attempting the same task, however the regex given below is giving me conflicting results:

$text = "Jiaaah.. RT @mizter_popo";

$pattern = "/(^|[ ])(\RT(?=\s))/";

if(preg_match($pattern, $text)) {
    echo "correct";
} else {
    echo "wrong";
}

I am expected this to give 'correct'. Running this in a PHP script on my local server and here returns 'wrong'. Running the same logic here returns 'correct'? Can anyone help explain what is going on? Or maybe I am wrong to expect 'correct' to be echoed?

Upvotes: 0

Views: 1735

Answers (3)

Cylian
Cylian

Reputation: 11181

This code would work

if (preg_match('/(?<=^|\s)RT(?=\s)/', $subject)) {
    # Successful match
} else {
    # Match attempt failed
}

but the site you mentioned not supporting this anyway.

Upvotes: 0

Chris Trahey
Chris Trahey

Reputation: 18290

I found a pattern which uses an assertion instead of the look-behind. There is alternation as well, but I bet that could be factored into the assertion with someone a little more REGEX talented than I...

$pattern = "/(^RT)|((?<=[ ])RT)/";

Upvotes: 0

John C
John C

Reputation: 8415

For me, removing the \ before the RT works on both in this specific instance:

$pattern = "/(^|[ ])(RT(?=\s))/";

It is possible the regex tester site are doing some heavy sanitisation to make sure people don't break their site, which may skew what works and what doesn't.

Upvotes: 1

Related Questions