i.c
i.c

Reputation: 17

PHP Regular Expression Exclusion

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?

Upvotes: 0

Views: 47

Answers (1)

The fourth bird
The fourth bird

Reputation: 163207

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

Upvotes: 1

Related Questions