Malixxl
Malixxl

Reputation: 525

PHP regex 2 different pattern and 2 different replacement

i'm quite newbie about regex i'm trying to replace 2 or more commas to one and deleting the last comma.

    $string1=  preg_replace('(,,+)', ',', $string1);
    $string1= preg_replace('/,([^,]*)$/', '', $string1);

my quesiton is: Is there any way to do this with a single line of regex?

Upvotes: 2

Views: 125

Answers (2)

Tim Pietzcker
Tim Pietzcker

Reputation: 336108

Yes, of course that's possible:

$result = preg_replace(
    '/(?<=,)   # Assert that the previous character is a comma
    ,+         # then match one or more commas
    |          # or
    ,          # Match a comma
    (?=[^,]*$) # if nothing but non-commas follow till the end of the string
    /x', 
    '', $subject);

Upvotes: 5

g13n
g13n

Reputation: 3246

No, it is not possible since the replacements are different and the two commas may or may not be at the end of the string.

That said, preg_replace() accepts an array of patterns and replacements so you could do that like:

preg_replace(array('/,,+/', '/,$/'), array(',', ''), $string1);

Note that I modified the second pattern. Hope that helps.

Upvotes: 0

Related Questions