Home > Back-end >  PHP Regular Expression Exclusion
PHP Regular Expression Exclusion

Time:11-11

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?

CodePudding user response:

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
  • Related