kexxcream kexxcream - 4 months ago 11
PHP Question

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.

Answer

Use:

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