Coincidencia de caracteres específicos precedidos por un espacio o nada Regex

Siguiendo esto 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 aquí returns 'wrong'. Running the same logic aquí returns 'correct'? Can anyone help explain what is going on? Or maybe I am wrong to expect 'correct' to be echoed?

preguntado el 04 de julio de 12 a las 05:07

3 Respuestas

Para mí, quitar el \ antes de 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.

Respondido 04 Jul 12, 05:07

Perfect! I should've realised an online tester would do that. Thank you! - djderek

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)/";

Respondido 04 Jul 12, 05:07

ah I hadn't thought about it from that perspective. Thanks - djderek

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.

Respondido 04 Jul 12, 05:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.