13

i am trying this code but i get this error: No ending delimiter '/' found

$form = " 2000,50";
$salary = preg_replace('/',', '.'/', $form); // No ending delimiter '/' found 
echo $salary;

I am not sure about the regex validation.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
daniel__
  • 11,633
  • 15
  • 64
  • 91

5 Answers5

73

Regex is overkill for replacing just a single character. Why not just do this instead?

str_replace(',', '.', $form);
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • 3
    Indeed. Why use a power drill with 12 thousand attachments when a screw driver suffices? – Bob_Gneu Jun 14 '11 at 16:46
  • 1
    @Midas: It seems to be a trend for basic answers to receive disproportionate amounts of upvotes on SO. http://stackoverflow.com/questions/4080265/what-does-this-css-do/4080268#4080268 and most of my top answers are examples. – BoltClock Jun 14 '11 at 16:55
  • In this instance, str_replace() performs a little more than 4 times faster than preg_replace(), so str_replace() is clearly the best choice. – Rob Raisch Jun 14 '11 at 18:32
6
$salary = preg_replace('/,/', '.', $form);

But yeah, you don't really want to match a pattern but a string which is constant, so simply use str_replace().

Midas
  • 7,012
  • 5
  • 34
  • 52
3

You can simply use

str_replace(',','.',$form);
ArtoAle
  • 2,939
  • 1
  • 25
  • 48
1

I don't understand your parameters -- I'm not sure what's supposed to be in the string and what isn't. But for preg_replace, the search pattern should be a string, and with the string also begin and end with a delimiter (typically '/'). I think it's redudant to need slashes round the search string when it's already inside a string, but that's how it works.

The second parameter should be a string containing the full stop and nothing else. This gives:

$salary = preg_replace( '/,/' , '.' , $form);

Other people are correct that str_replace will be fine for turning one character into another, but if the replacement you want gets more complicated preg_replace will be reasonable.

Jack V.
  • 1,381
  • 6
  • 20
0

The '/' in your string is used as a start-of-regex delimiter so you need to escape it. The correct line should read:

$salary = preg_replace('\\/',', '.'/', $form);

I'm also curious why the second param is ', ' . '/' rather than ', /'.

EDIT

Ahh I see now, the line should read:

$salary = preg_replace( '/,/', '.', $form);

I was confused because the first comma in your example should be a '.' to concat the string.

Rob Raisch
  • 17,040
  • 4
  • 48
  • 58