Daniel
Daniel

Reputation: 21

PHP regexp not working

I want to match "TEST:" in the following example:

$text = "TEST:

This is a test.";

preg_match_all("/^([A-Z]+)\:$/m", $text, $matches);

But $matches is empty.

This however does work:

$text = "TEST:

This is a test.";

preg_match_all("/^([A-Z]+).*\:*$/m", $text, $matches);

Output:

Array
(
    [0] => Array
        (
            [0] => TEST:
            [1] => This is a test.
        )

    [1] => Array
        (
            [0] => TEST
            [1] => T
        )

)

But I only want it to match "TEST:".

What am I doing wrong here? It seems to have a problem with the colon in the pattern, but doesn't work either if I don't escape it.

Thanks for help!

Upvotes: 0

Views: 58

Answers (1)

Ph.T
Ph.T

Reputation: 616

Actually when you use $ to denote the end of the line, be VERY carefull from where the string is build: On windows, an end-of-line is \r\n while on unix it is \n only The $ end delimiter ONLY recognize \n as an end of line

$text = "TEST:

This is a test.";
$text = str_replace("\r", "", $text);

preg_match_all("/^([A-Z]+)\:$/m", $text, $matches);

will work perfectly

Upvotes: 2

Related Questions