Replacing Spaces with Underscores

前端 未结 12 505
北海茫月
北海茫月 2020-11-30 20:14

I have a PHP Script that users will enter a name like: Alex_Newton,

However, some users will use a space rather than an underscore, so my question is:

相关标签:
12条回答
  • 2020-11-30 21:07

    I used like this

    $option = trim($option);
    $option = str_replace(' ', '_', $option);
    
    0 讨论(0)
  • 2020-11-30 21:10

    As of others have explained how to do it using str_replace, you can also use regex to achieve this.

    $name = preg_replace('/\s+/', '_', $name);
    
    0 讨论(0)
  • 2020-11-30 21:10

    Use str_replace function of PHP.

    Something like:

    $str = str_replace(' ', '_', $str);
    
    0 讨论(0)
  • 2020-11-30 21:11
    $name = str_replace(' ', '_', $name);
    
    0 讨论(0)
  • 2020-11-30 21:14

    str_replace - it is evident solution. But sometimes you need to know what exactly the spaces there are. I have a problem with spaces from csv file.

    There were two chars but one of them was 0160 (0x0A0) and other was invisible (0x0C2)

    my final solution:

    $str = preg_replace('/\xC2\xA0+/', '', $str);
    

    I found the invisible symbol from HEX viewer from mc (midnight viewer - F3 - F9)

    0 讨论(0)
  • 2020-11-30 21:15

    Strtr replaces single characters instead of strings, so it's a good solution for this example. Supposedly strtr is faster than str_replace (but for this use case they're both immeasurably fast).

    echo strtr('Alex Newton',' ','_');
    //outputs: Alex_Newton
    
    0 讨论(0)
提交回复
热议问题