kexxcream
kexxcream

Reputation: 5943

Matching 3 last numbers in a string with regex

Problem:

Trying to highlight the last 3 numbers in a string using regular expression.

Code:

<?php
    show_source('regex.php');

    $string = "
        780155OVERF I000000
        TRANFER DOMESTIC
        000114
        STHLM SE AB
    ";
?>
<!DOCTYPE html>
<html>
    <head>
        <title>Regex to match last 3 numbers</title>
        <meta charset="utf-8">
    </head>
    <body>
        <?php
            echo nl2br(str_replace('/\d{3}(?=[^\d]+$)/g', '<span style="background-color:red;">$1</span>', $string));
        ?>
    </body>
</html>

Desired outcome:

The numbers 114 should have red background color.

Upvotes: 0

Views: 88

Answers (2)

JustOnUnderMillions
JustOnUnderMillions

Reputation: 3795

Use:

print nl2br(
        preg_replace('/\d{3}(?=[^\d]+$)/s', 
                     '<span style="background-color:red;">$0</span>', 
                     $string)
           );

Upvotes: 1

u_mulder
u_mulder

Reputation: 54841

Main error: str_replace doesn't work wit regexes. Use preg_replace:

$string = "
    780155OVERF I000000
    TRANFER DOMESTIC
    000114
    STHLM SE AB
";

// use `m` modifier as you have multiline string
// `g` modifier is not supported by preg_replace
echo preg_replace("/\d{3}(?=[^\d]+)$/m", '<span>$0</span>', $string);

Upvotes: 2

Related Questions