Zhlobopotam
Zhlobopotam

Reputation: 173

Preg_replace for price string (PHP)

Trying to convert a string with some price "2 200,00" (without quotes) to look like 2200.

$result = preg_replace("/([^0-9,]s)/iu","", $result);

Doesn't work. Could sombody help, pls?

Upvotes: 2

Views: 1782

Answers (5)

andyb
andyb

Reputation: 43823

Regex is not required for this.

$number = '2 200,00';
echo str_replace(array(' ', ','), '', substr($number, 0, strrpos($number, ',')));

(If the number string always contains a comma)

Upvotes: 0

Francois Deschenes
Francois Deschenes

Reputation: 24989

You can do this with intval and str_replace instead of preg_replace.

// Results in 2200 (without decimals)
$result = intval(str_replace(' ', '', $result));

Upvotes: 0

Tudor Constantin
Tudor Constantin

Reputation: 26861

Try with

$result = preg_replace("/[,\s+]/iu","", $result);

Upvotes: 1

stema
stema

Reputation: 93026

Whats the s good for? And the brackets are also not needed. Try

$result = preg_replace("/[^0-9,]+/iu","", $result);

Probably better to watch only for whitspaces

$result = preg_replace("/\w+/iu","", $result);

+ means match one ore more, i.e. if there is more than one whitespace it would be matched at once.

Upvotes: 2

Related Questions