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?
My Answer:
To exclude numbers that are preceded by a dollar sign, you can modify the regular expression pattern to include a negative lookbehind assertion for the dollar sign. Here is the updated code:
php
$str = '10,000.1 $100,000.1';
$pattern = '/(?
$replacement_str = 'Without$sign';
echo preg_replace($pattern, $replacement_str, $str);
?>
By adding `(?
Rate this post
5 of 5 based on 1891 votesComments