Regex help pleeeasssee!

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Leo Andrews

    #1

    Regex help pleeeasssee!

    Hi,

    I should firstly say I'm terrible at regular expressions - I know the
    PHP functions, I just can't make them come alive. And I've got the
    O'Reilly's regex book!

    I've got a string and I want to:
    * Replace spaces with the underscore character
    * Remove any character which isn't A-Z, a-z 0-9

    Should be really simple, right? I hope so and if anyone can help then
    I'd be hugely grateful.

    Thanks
    Leo.
  • John Dunlop

    #2
    Re: Regex help pleeeasssee!

    Leo Andrews wrote:
    [color=blue]
    > I've got a string and I want to:
    > * Replace spaces with the underscore character[/color]

    str_replace(' ','_',$subject)

    Every parameter can be an array, so you can give it an array
    of spaces, tabs, newlines, etc.

    Replace all occurrences of the search string with the replacement string

    [color=blue]
    > * Remove any character which isn't A-Z, a-z 0-9[/color]

    preg_replace('`[^a-zA-Z0-9]`','',$subject)

    The pattern is made up of a single character class, which
    finds characters not belonging to the sets a-z, A-Z, and 0-9,
    and replaces them with the empty string. The PCREs `[^a-z0-
    9]`i and `[^a-z\d]`i are equivalent.

    --
    Jock

    Comment

    • juglesh

      #3
      Re: Regex help pleeeasssee!

      I use this to clean up user input for foldernames:
      ( in the 3rd one down, just change the - to a _ if you you'd rather)
      <?php
      // clean up the user specified foldername
      $foldername = stripslashes ( $_POST['foldername'] );
      //This erase white-spaces on the beginning and the end in each line of
      a string:
      $foldername = preg_replace('~ ^(\s*)(.*?)(\s* )$~m', "\\2", $foldername);
      //erases all NON-alfanumerics
      $foldername = ereg_replace("[^[:alnum:] ]","-",$folderna me);
      // take out repetative spaces??:
      $foldername = preg_replace('/\s\s+/', ' ', $foldername);
      if ($foldername == ""){$folder name = "untitled"; }
      ?>

      Comment

      Working...