Here is a very handy PHP function to convert the contents of a string into an SEO ready, browser-friendly URL. This can be used within article creation in conjunction with .htaccess ‘RewriteRule’.
function string_to_url($string_name, $length, $file_extension)
{
$file_name = ereg_replace(”[^a-z^A-Z^0-9^ ^-]“, “”, $string_name);
$file_name = strtolower($file_name);
$file_name = preg_replace(’/\s+/’, ” “, $file_name);
$file_name = substr($file_name, 0, $length);
$file_name = trim($file_name);
$file_name = str_replace(” “, “-”, $file_name);
$file_name = $file_name.$file_extension;
return $file_name;
}
Example usage:
<?php
$my_string = ” String to URL @~{* &^”;
$url = string_to_url($my_string, 150, “.html”);
echo $url;
?>
This would parse as:
string-to-url.html
Function break-down
So, what does this function do (in order)?
- All illegal, none url characters are stripped away
- Characters are forced to lowercase
- Duplicate spaces are removed
- The string is shortened by the value of $length
- Any spaces at the end or start of the string are removed with trim
- Remaining spaces are replaced with SEO friendly ‘-’ hyphens
- The file extension is added to the string