Tuesday, 15 April 2014

regex - PHP using preg_replace on every number in string -



regex - PHP using preg_replace on every number in string -

say have multiline string like

a: 51 b: 221 c: 45

and want replace get

a: $51 b: $221 c: $45

i tried

preg_replace("/[\d*][^0-9]*/","$currency$0",$pricelist);

but prepends currency symbol before every digit instead of every number. tried

preg_replace("/[\d]*/","$currency$0",$pricelist);

but surrounds amount 2 currency symbols.

use + quantifier instead of *:

preg_replace("/\d+/", "$currency$0",$pricelist);

using * quantifier, regex first matches digits, , matches empty string after lastly digit. hence see 2 $ symbols - 1 before digits matched, , 1 before empty string matched after lastly digit.

php regex

No comments:

Post a Comment