String to URL – PHP function

String to URL - PHP function

Here’s a useful method for converting any php string into a browser/SEO¬†friendly URL. The string to URL function can be used as reference when generating pages and is a very powerful companion if you use .htaccess to ‘RewriteBase’ your links.

String to URL function

First off, let’s create the function container:

/// STRING TO URL
function string_to_url()
{
}
///

Now, we need to clean up any string that passes through this function:

/// STRING TO URL
 function string_to_url($string_name)
 {
 $file_name = ereg_replace("[^a-z^A-Z^0-9^ ^-]", "", $string_name);/// ALLOWED CHARS
 $file_name = strtolower($file_name); /// CHANGE STRING TO LOWERCASE
 $file_name = preg_replace('/s+/', " ", $file_name); /// REMOVE MULTIPLE SPACES
 }
 ///

Now to put the finishing touches to our function:

/// STRING TO URL
function string_to_url($string_name)
{
 $file_name = ereg_replace("[^a-z^A-Z^0-9^ ^-]", "", $string_name); /// ALLOWED CHARS
 $file_name = strtolower($file_name); /// CHANGE STRING TO LOWERCASE
 $file_name = preg_replace('/s+/', " ", $file_name); /// REMOVE MULTIPLE SPACES
 $file_name = substr($file_name, 0, 150); /// SHORTEN TO 150 CHARS
 $file_name = trim($file_name); /// TRIM TRAILING SPACES
 $file_name = str_replace(" ", "-", $file_name); /// CHANGE SPACES TO HYPENS
 return $file_name; /// RETURN STRING TO URL
}
///

To use this function:

/// DON'T FORGET PLACE YOUR STRING_TO_URL FUNCTION BEFORE THE FOLLOWING PHP
$My_string = "Hello, you lovely monkey!";
echo string_to_url($My_string)."html";

This will output:

hello-you-lovely-monkey.html

Leave a Reply

Your email address will not be published. Required fields are marked *