Regex help pleeeasssee!

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

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.


Re: Regex help pleeeasssee!

Leo Andrews wrote:

Quoted text here. Click to load it

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

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

Quoted text here. Click to load it


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.


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)
// 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', "", $foldername);
//erases all NON-alfanumerics
$foldername = ereg_replace("[^[:alnum:] ]","-",$foldername);
// take out repetative spaces??:
$foldername = preg_replace('/\s\s+/', ' ', $foldername);
if ($foldername == ""){$foldername = "untitled";}

Site Timeline