PHP Regular Expression Exclusion

Issue

Here is the sample PHP code:

<?php
$str = '10,000.1 $100,000.1';
$pattern = '/(?!\$)\d+(,\d{3})*\.?\d*/';
$replacement_str = 'Without$sign';
echo preg_replace($pattern, $replacement_str, $str);?>

Target is to replace numbers only (i.e. "$100,000.1" should not be replaced). But the above code replaces both 10,000.1 and $100,000.1. How to achieve the exclusion?

Solution

This assertion is always true (?!\$)\d+ as you match a digit which can not be a $

As the . and the digits at the end of the pattern are optional, it could also match ending on a dot like for example 0,000.

Instead you can assert a whitespace boundary to the left, and optionally match a dot followed by 1 or more digits:

(?<!\S)\d+(?:,\d{3})*(?:\.\d+)?\b

Regex demo

Example:

$str = '10,000.1 $100,000.1';
$pattern = '/(?<!\S)\d+(?:,\d{3})*(?:\.\d+)?\b/';
$replacement_str = 'Without$sign';
echo preg_replace($pattern, $replacement_str, $str);

Output (If you remove the numbers, the text "Without$sign" is not correct)

Without$sign $100,000.1

Answered By – The fourth bird

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published