Format text into a SEO Friendly String

Posted on August 28, 2008, under PHP,  Bookmark it

Hi,

This function takes a regular phrase and formats it into a seo friendly string which can be part of an URL.

<?php
function friendly_seo_string($string, $separator = '-')
{
$string = trim($string);

$string = strtolower($string); // convert to lowercase text

// Recommendation URL: http://www.webcheatsheet.com/php/regular_expressions.php

// Only space, letters, numbers and underscore are allowed

$string = trim(ereg_replace("[^ A-Za-z0-9_]", " ", $string));

/*

"t" (ASCII 9 (0x09)), a tab.
"n" (ASCII 10 (0x0A)), a new line (line feed).
"r" (ASCII 13 (0x0D)), a carriage return. 

*/

$string = ereg_replace("[ tnr]+", "-", $string);

$string = str_replace(" ", $separator, $string);

$string = ereg_replace("[ -]+", "-", $string);

return $string;
}

$str = friendly_seo_string('Lorem Ipsum is simply dummy text.');

// Outputs: lorem-ipsum-is-simply-dummy-text
echo $str;
?>

This string can be added to a friendly URL like this:

http://www.yourdomain.com/info/lorem-ipsum-is-simply-dummy-text.html

Recommendation URLs:

http://www.webcheatsheet.com/php/regular_expressions.php

http://www.php.net/manual/function.ereg-replace.php

Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!

Get our RSS Feed!

2 Replies to "Format text into a SEO Friendly String"

  1. [...] many parameters in an URL can create problems in crawling for a Search Engine. A friendly optimised URL would always be a better alternative if this option is available to you. These URLs [...]

  2. Function ereg_replace() is deprecated
    http://php.net/manual/en/function.ereg-replace.php

    You would need to update the method to use the preg_replace().

    function friendly_seo_string($string, $separator = ‘-’){    $string = trim($string);    // convert to lowercase text    $string = strtolower($string);     // Only space, letters, numbers and underscore are allowed    $string = trim(preg_replace(“{[^ A-Za-z0-9_]}”, ” “, $string));    /* “t” (ASCII 9 (0×09)), a tab.     * “n” (ASCII 10 (0x0A)), a new line (line feed).     * “r” (ASCII 13 (0x0D)), a carriage return. */    $string = preg_replace(“{[ tnr]+}”, “-”, $string);    $string = str_replace(” “, $separator, $string);    $string = preg_replace(“{[ -]+}”, “-”, $string);    return $string;}

Leave a Reply


* = required fields

  (will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Note: If you want to post CODE Snippets, please make them postable first!
(e.g. <br /> should be converted to &lt;br /&gt;)