Replace Comma(,) with Dot(.) RegEx php

前端 未结 5 1194
遇见更好的自我
遇见更好的自我 2021-01-02 01:24

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

$form = \" 2000,50\";
$salary = preg_replace(\'/\',\', \'.\'/\', $f         


        
相关标签:
5条回答
  • 2021-01-02 01:48

    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.

    0 讨论(0)
  • 2021-01-02 01:50

    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.

    0 讨论(0)
  • 2021-01-02 01:55

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

    str_replace(',', '.', $form);
    
    0 讨论(0)
  • 2021-01-02 02:10
    $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().

    0 讨论(0)
  • 2021-01-02 02:11

    You can simply use

    str_replace(',','.',$form);
    
    0 讨论(0)
提交回复
热议问题