Tuesday 2 June 2015

Creating SEO URL from user input in PHP

How to create a SEO URL from user input, for web 2.0 style sites which use Apache's mod rewrite

<?php
function make_seo_title($str)
{
 // html decode, in case it is coming encoded (AJAX request)
 $seo_title = rawurldecode($str);
 // some characters that might create trouble
 $switch_chars = '(,),\,/';
 $sc = explode(',', $switch_chars);
 foreach ($sc as $c) $seo_title = str_replace($c, '-', $seo_title);
 // leave only alphanumeric characters and replace spaces with hyphens
 $seo_title = strtolower(str_replace('--', '-', preg_replace('/[\s]/', '-', preg_replace('/[^[:alnum:]\s-]+/', '', $str))));
 $len = strlen($seo_title);
 if ($seo_title[$len - 1] == '-') $seo_title = substr($seo_title, 0, -1);
 if ($seo_title[0] == '-') $seo_title = substr($seo_title, 1, $len);
 return $seo_title;
}
?>
 

Usage

Mostly used with MVC patterns in PHP this is a simple function to generate a search engine friendly, aka SEO, URL from an article page by using the input title field for example.

Pass the value of the field you will be using as the title.
 

0 comments:

Post a Comment