Page 1 of 1

Is there a simple'r way to regex this

Posted: Wed Oct 14, 2009 8:09 am
by arminium
Hi guys,

Regex is not my first or 2nd language

Im trying to clean up form data $_POST['pagename'], for a CMS page name field.......ie, remove non-alphanumeric characters, double spaces/hyphens and tags etc, and replace space and underscores with hyphens

So far i have this and it works, but is there a cleaner way to do it

Code: Select all

 
//string used  -->   Some test_txt^   with %$ symbols and 1233 numbers<p>`\'\"</p>
$MyStr = (string) trim(strip_tags($_POST['pagename']));
 
$MyStr = preg_replace('/[^a-zA-Z0-9\s-_]/', '', $MyStr);
$MyStr = str_replace('_', ' ', $MyStr);
$MyStr = preg_replace('/\\s/', '-', $MyStr);
 
echo $MyStr;
 
// result is --> Some-test-txt-with-symbols-and-1233-numbers
 
 
Thanks in advance

Re: Is there a simple'r way to regex this

Posted: Wed Oct 14, 2009 5:06 pm
by arminium
Hey thanks Mc,

I missed the cases of the beginning and end hyphens

I have condensed your code and this is working, and is tidy and clean, and working on my dozen test examples

Code: Select all

 
$str = (string) trim(preg_replace('/[^a-z0-9]+/i', '-', strip_tags([color=#00FF00]$String_to_clean_here[/color])), '-');
 
 
Hope this will help others too, i have a seen questions like this for sanitising Page names before