Forum Moderators: coopster
I am trying to create a clean URL rewrite by specifying the title in the URL, example http:mydomain/news/this-is-an-article.
I am trying to clean a string (to check for human error input) so that it remove any space in front or back of the string, put everything in lowercase, allow only from a to z and 0 to 9 and replace any space with a minus sign.
It is working fine, but when I enter something like '($%($#*%(#$%&*()#$* Testing test'...
The result is coming as '-testing------------test-'
The code I am using is below. Thanks in advance for your help.
function StripExtraSpace($s)
{
for($i = 0; $i < strlen($s); $i++)
{
$newstr = $newstr . substr($s, $i, 1);
if(substr($s, $i, 1) == ' ')
while(substr($s, $i + 1, 1) == ' ')
$i++;
}
return $newstr;
}
// clean string from special characters, make all lower case and replace spaces with -
function create_extract($uncleanstring)
{
$cleanstring = preg_replace('/[^0-9@.a-z ]+/i', '', (strtolower($uncleanstring)));
$cleanstringfromspaces = StripExtraSpace($cleanstring);
$formatcleanstring = str_replace(" ", "-", $cleanstringfromspaces);
return $formatcleanstring;
}
Depending on where you decide is best to put it you could use:
/* Replace 2 or more -s with one */
preg_replace('#-{2,}#','-',$string);
OR
/* Replace 2 or more spaces with one */
preg_replace('#\s{2,}#',' ',$string);
BTW: Welcome to WebmasterWorld!
In looking a bit closer you could do it like this:
$cleanstring = preg_replace('/[^0-9@.a-z ]+/i', '', (strtolower($uncleanstring)));
$cleanstring = preg_replace('#\s{2,}#',' ',$cleanstring);
Keep in mind you could change your replaces and replacements to arrays $replace & $replacement with the respective values for each if you like...
Thanks a lot for the help, worked like a charm!
Thanks for the welcome. This is a great forum :)