Page 1 of 1

preg_replace more than one character at a time

Posted: Wed Apr 11, 2012 9:20 am
by simonmlewis

Code: Select all

 $title = "$row->title"; 
 $findtitle ="/ /"; 
 $replacetitle ="-"; 
 $titlereplace = preg_replace ($findtitle, $replacetitle, $title); 
I have a problem where the title may contain spaces of course, but may also contain forward slashes.

I can go through the current DB to get rid of them, but these are idiots are will easily add more slashes. So is there a way I can do the $findtitle to look for spaces (like it does now) AND "/" in one go? Then $replacetitle replaces the spaces AND slashes with a "-"??

Re: preg_replace more than one character at a time

Posted: Wed Apr 11, 2012 9:23 am
by Celauran

Code: Select all

$findtitle = '/[ \/]/';

Re: preg_replace more than one character at a time

Posted: Wed Apr 11, 2012 9:24 am
by simonmlewis
Crikey that was fast. Can you explain the method please?

Re: preg_replace more than one character at a time

Posted: Wed Apr 11, 2012 9:34 am
by Celauran
The regex matches anything enclosed in the brackets; in this case, a space and an escaped slash. You can append additional characters as needed.

Re: preg_replace more than one character at a time

Posted: Wed Apr 11, 2012 9:37 am
by simonmlewis
Oh I see, so if I put a ? in there, before the space or after the forward slash, it would then convert the ? into whatever I choos ein the latter part of the script?

Re: preg_replace more than one character at a time

Posted: Wed Apr 11, 2012 9:41 am
by Celauran
Yes, though you'd need to escape the ?

Re: preg_replace more than one character at a time

Posted: Wed Apr 11, 2012 9:43 am
by simonmlewis
How do I know which characters I must escape? ie. is it just special characters and not alphanum?

?:'{})(*&...etc..?

Re: preg_replace more than one character at a time

Posted: Wed Apr 11, 2012 9:46 am
by Celauran