Reputation: 2960
I m trying to remove price from string via preg_replace with regular expression but it is not working. i want to remove 202,00 from given string
<?php
$haystack = "4 x 3XS - € 202,00, L, 2XS, 4 x XS - € 202,00, S";
echo preg_replace('/^(?:0|[1-9]\d*)(?:\,\d{2})?$/','',$haystack);
?>
Expected result:
4 x 3XS, L, 2XS, 4 x XS, S
Any help will be appreciated.
Upvotes: 0
Views: 312
Reputation: 47991
Since this task merely requires the sanitation of a predictably formatted string (it is not a validation task), you do not need to carefully match the price substring; just match from the price start (space-hyphen) to the price finish (before the next comma-space).
Code: (Demo)
echo preg_replace('/ -(?:(?!, ).)*/', '', $haystack);
For anyone scared off by regex, you can also explode, grab leading substrings, then re-implode. Demo
echo implode(
', ',
array_map(
fn($v) => strstr($v . ' -', ' -', true),
explode(', ', $haystack)
)
);
Upvotes: -1
Reputation: 627110
You may use
$haystack = "4 x 3XS - € 202,00, L, 2XS, 4 x XS - € 202,00, S";
echo preg_replace('/\s*(?:-\s*)?€\s*\d+(?:,\d+)?/u','',$haystack);
See the PHP demo online
Since the pattern contains Unicode char, it is safer to add u
modifier to the regex. The pattern matches
\s*
- 0+ whitespaces(?:-\s*)?
- an optional sequence of -
and 0+ whitespaces€
- a euro symbol\s*
- 0+ whitespaces\d+
- 1+ digits(?:,\d+)?
- an optional sequence of ,
and 1+ digits.Upvotes: 2
Reputation: 26198
You can use regular expression:
(?<=€\s)(\d*,?\d+)
(?<=€\s)
Lookbehind for €
symbol and whitespace.(\d*,?\d+)
Capture digits, comma optionally, digits.Your code becomes:
<?php
$haystack = "4 x 3XS - € 202,00, L, 2XS, 4 x XS - € 202,00, S";
echo preg_replace('/(?<=€\s)(\d*,?\d+)/','',$haystack);
?>
Output:
4 x 3XS - € L, 2XS, 4 x XS - € S
You can try it here.
Upvotes: 2