Is there a simple'r way to regex this

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
arminium
Forum Newbie
Posts: 18
Joined: Wed Aug 12, 2009 10:02 pm
Location: Sunshine Coast, AUSTRALIA!!!!!!

Is there a simple'r way to regex this

Post 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
User avatar
arminium
Forum Newbie
Posts: 18
Joined: Wed Aug 12, 2009 10:02 pm
Location: Sunshine Coast, AUSTRALIA!!!!!!

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

Post 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
Post Reply