1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

[String Transformation] All to Lowercase, Spaces to Underscores, Filter Bad Stuff

Discussion in 'PHP' started by ColorWP.com, Jun 21, 2010.

  1. #1
    Hello.

    I'd like to transfer a dynamic string called $string so that all the letters are converted to lowercase, all spaces are converted to underscore and everything different from numbers, letters and underscore should be removed. Also, white space from inside and around the string should be removed too if possible.

    I can start with:
    // remove bad characters here, everything else than numbers, letters and underscore from the string
    $string=strtolower($string);
    // white space should be removed here, including double and triple spaces between words, white space around the whole string, etc
    $string=str_replace(" ","_",$string);
    PHP:

     
    ColorWP.com, Jun 21, 2010 IP
  2. lukeg32

    lukeg32 Peon

    Messages:
    645
    Likes Received:
    19
    Best Answers:
    1
    Trophy Points:
    0
    #2
    As you asked for;

    $string="HEllo  world1234 ffas  9999()()  4fh";
    
    $string = preg_replace("/\s+/", " ", $string);
    $string = str_replace(" ", "_", $string);
    $string = preg_replace("/[^A-Za-z0-9_]/","",$string);
    $string=strtolower($string);
    
    print $string;
    PHP:
     
    lukeg32, Jun 21, 2010 IP
    www.Andro.ws likes this.
  3. ColorWP.com

    ColorWP.com Notable Member

    Messages:
    3,121
    Likes Received:
    100
    Best Answers:
    1
    Trophy Points:
    270
    #3
    Thank you very much, but can you just clarify the purpose of this line?:
     
    ColorWP.com, Jun 21, 2010 IP
  4. lukeg32

    lukeg32 Peon

    Messages:
    645
    Likes Received:
    19
    Best Answers:
    1
    Trophy Points:
    0
    #4
    It converts multiple spaces, into a single space instead; obviously not required if you dont mind having multiple underscores in their place :)
     
    lukeg32, Jun 21, 2010 IP