4

I have string

10.2, 200.3, 33.00

and I want it to be replaced as

10,2, 200,3, 33,00

I tried

preg_replace("/[.]$/","/\d[,]$/",$input);

but it is not replacing!

I can't use str_replace because it's task in university

user2287965
  • 203
  • 2
  • 6
  • 14
  • 3
    why not use [str_replace](http://php.net/manual/en/function.str-replace.php) – sachleen May 04 '13 at 18:05
  • `$` means end of subject, and is of no use here. – mario May 04 '13 at 18:05
  • 2
    this should be simple, you really shouldn't even need a regex for just replacing '.' with ',' – aaronman May 04 '13 at 18:05
  • @aaronman and how does your comment help OP? – sachleen May 04 '13 at 18:06
  • It doesn't, his question is dumb, that's why this is a comment not an answer – aaronman May 04 '13 at 18:07
  • _“I can't use str_replace because it's task in university”_ − so they are trying to make people more _stupid_ at your university …? :-p – CBroe May 04 '13 at 19:54
  • 1
    If you're learning this stuff at university and you're stuck, why can't you ask your tutor? Stackoverflow may give you a direct answer to the question at hand, but the tutor's job is to help you understand it, which is what you actually need. – Spudley May 04 '13 at 20:14

3 Answers3

15

Do not use regular expresion when dumb str_replace() suffices:

$str = str_replace('.', ',', $str)

See docs: http://php.net/str_replace

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
11
preg_replace('/\./', ',', $input); 

This would replace all . dots with ,.

preg_replace('/(\d+).(\d+)/', '$1,$2', $input); 

This is more specific to your need. $1 replaces first digit as in parenthesis; $2 replaces second.

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
VoidPointer
  • 3,037
  • 21
  • 25
2

You can try this

preg_replace('/[^0-9\s]/', ',', $input)

but it is better if you use

str_replace('.', ',', $input)

as Marcin answered.

smm
  • 527
  • 5
  • 17