Replacing Spaces with Underscores

前端 未结 12 504
北海茫月
北海茫月 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 20:56
    $name = str_replace(' ', '_', $name);
    

    http://php.net/manual/en/function.str-replace.php

    0 讨论(0)
  • 2020-11-30 20:56

    Call http://php.net/str_replace: $input = str_replace(' ', '_', $input);

    0 讨论(0)
  • 2020-11-30 20:59

    you can use str_replace say your name is in variable $name

    $result = str_replace(' ', '_', $name);
    

    another way is to use regex, as it will help to eliminate 2-time space etc.

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

    You can also do this to prevent the words from beginning or ending with underscores like _words_more_words_, This would avoid beginning and ending with white spaces.

    $trimmed = trim($string); // Trims both ends
    $convert = str_replace('', '_', $trimmed);
    
    0 讨论(0)
  • 2020-11-30 21:02

    This is part of my code which makes spaces into underscores for naming my files:

    $file = basename($_FILES['upload']['name']);
    $file = str_replace(' ','_',$file);
    
    0 讨论(0)
  • 2020-11-30 21:04

    Use str_replace:

    str_replace(" ","_","Alex Newton");
    
    0 讨论(0)
提交回复
热议问题