Battery
Battery

Reputation: 397

Replace percent (symbol and value) and brackets

I receive from the client a string like this one:

"a, b, c, d 5%, e, f, g 76%, h (string,string), i"

I want to create a regExp that can remove from the string 5%, 76% (and any other possible percent value n%) and the brackets (bracket opening is replaced by comma). The desired result is:

"a, b, c, d, e, f, g, h, string, string, i"

Is this possible with PHP?

Upvotes: 1

Views: 6264

Answers (5)

Timothée Groleau
Timothée Groleau

Reputation: 1960

Your definition of the braces is a bit unclear, but if I assume there's no other opening an closing braces, use this:

$line = "a, b, c, d 5%, e, f, g 76%, h (string,string), i";
$line = preg_replace('/\s+\d+%/', '', $line);
$line = preg_replace('/\s*\(/', ', ', $line);
$line = preg_replace('/\s*\)\s*/', '', $line);
$line = preg_replace('/,(\S)/', ', $1', $line);
echo $line;

Upvotes: 1

You would like to use this code:

preg_replace('/ *\d*\%/','', 'a, b, c, d 5%, e, f, g 76%, h (string,string), i');

Here is example (switch to replace tab and clean the replace text)

Upvotes: 0

NickSun
NickSun

Reputation: 1

$string = "a, b, c, d 5%, e, f, g 76%, h (string,string), i";
$string = preg_replace('/\s+\d+%|\)/', '', $string);
$string = str_replace('(', ',', $string);
$string = preg_replace('/\s*,\s*/', ', ', $string);

Upvotes: 0

codaddict
codaddict

Reputation: 455272

$cleaned = preg_replace('/[%()]/', '', $input)

Upvotes: 3

DhruvPathak
DhruvPathak

Reputation: 43245

Yes this is possible with PHP, use this function : http://php.net/manual/en/function.preg-replace.php

You will need to write a regular expression to match your criteria.

Upvotes: 1

Related Questions