Skip to content
WJunction - Webmaster Forum

[PHP] Creating an SEO URL Function

Status
Not open for further replies.
Ok so here's a tutorial on creating a PHP function to encode urls ready for the URI

This was posted originally as a reply and i thought it would be helpful to others

I think you have to take into consideration of Encodings aswell

so preg match will work to an extent but there are alternative solutions that will convert other encodings and chars to a human-readable string.

Ok lets just get started by creating a function!

PHP:
function URL_CovertString($inputString)
{
   
}

Ok so lets just make a list of what we need to do to the string

  • Remove no UTF-8 Alphanumeric's
  • Convert Foreign chars to a readable human form
  • Replace 2 or more spaces with 1 single space
  • Replace single spaces with the separator ( - )

Ok lets just get started with what functions we will use to accomplish this!

preg_replace, to replace char's and use ASCII/TRANSLIT
trim, self explainable
iconv, Performs a character set conversion on the string str from in_charset to out_charset.

Ok so lets put it in the function and get it working.

PHP:
function URL_CovertString($inputString)
{
    $inputString = preg_replace('~[^\\pL0-9_]+~u', '-', $inputString);
    $inputString = trim($inputString, "-");
    $inputString = iconv("utf-8", "us-ascii//TRANSLIT", $inputString); 
    return preg_replace('~[^-a-z0-9_]+~i', '', $inputString); 
}

Ok so the first preg_replace substitutes anything but letters, numbers and '_' with separator.

trim will trim the space around the separator.

iconv will translate incompatible encoding into compatible coding, does the whole job ;)

And final preg_replace will remove anything but -_ a-z and 0-9, leaving the string seperated by a dash.

Any improvements you can make without making the function to slow may be added
 

1 comment

Thank you.. I will give it a whirl on PHPBB 3.07_pl. I was looking for this and thank you so much for the clear explanation!
 
Status
Not open for further replies.

About the author

L
Active Member · Joined
I am a skilled programmer within PHP,HTML,CSS,MYSQL and also the owner of several websites Programming, Football...
1,367
Messages
1
Reactions
38
Points

Advertise on WJunction

Reach 1000's of webmasters, hosts & affiliates. Banner & sponsored-thread slots available.

Contact us
Back
Top Bottom