Reputation: 5943
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
Reputation: 3795
Use:
print nl2br(
preg_replace('/\d{3}(?=[^\d]+$)/s',
'<span style="background-color:red;">$0</span>',
$string)
);
Upvotes: 1
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