Link to home
Start Free TrialLog in
Avatar of Fernanditos
Fernanditos

asked on

Great PHP Function to create Slug - SEO Frindly URLs, like Wordpress slug

Hi,

Could some expert please help me out with a good quality PHP function named slug() to convert any text string into a clean SEO friendly URL, and remove common words.

Example:

$excluded = "is,the,by,in,a,to"
$PostTitle= "This//:?0¿= is á Tést...---,,,() to create ºúrl"

echo slug($PostTitle);

result: "this-test-create-url"

Thank you!


Avatar of xterm
xterm

How about this?
<?php

function slug($PostTitle) {
  $excluded = "is,the,by,in,a,to";
  $array_excluded = explode(",",$excluded);
  for ($i=0; $i<sizeof($array_excluded); $i++) {
    $PostTitle=str_replace(" $array_excluded[$i] ","",$PostTitle);
  }
  return($PostTitle);
}

$PostTitle="This//:?0¿= is á Tést...---,,,() to create ºúrl";
$result=slug("$PostTitle");

echo "Title:  $PostTitle\n";
echo "Slugged:  $result\n";

?>

Open in new window

Yes, that is a nice addition by babuno5 - I would filter $PostTitle through that function as well, or build it into my proposed slug() function.
try this code

Open in new window

function generateSlug($phrase, $maxLength)
{
$result = strtolower($phrase);

$result = preg_replace("/[^a-z0-9\s-]/", "", $result);
$result = trim(preg_replace("/[\s-]+/", " ", $result));
$result = trim(substr($result, 0, $maxLength));
$result = preg_replace("/\s/", "-", $result);


$search  = array('is','the','by','in','a','to');
$result = str_replace($search, '', $subject);

return $result;

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Fernanditos

ASKER

Thank you all for the solutions provided!

@Ray, your solution meets perfect my need, there is only one small detail to make it perfect:

If there is white space in the beginning or end of string I will get it replaced too by a "-"

E.G $str = "http:// www .elsábado,.;=?¿0¿?¿)()/&%$ is here ";

Result: -elsabado-here-

How to remove the "-" from both cases ?

Thank you so much1
$bad='is,the,by,in,a,to,http,www,heres'
Fernanditos

you can remove dash from both case with following function:
function trimString($input, $string){
        $input = trim($input);
        $startPattern = "/^($string)+/i";
        $endPattern = "/($string)+$/i";
        return trim(preg_replace($endPattern, '', preg_replace($startPattern,'',$input)));
} 

Open in new window


echo trimString('-elsabado-here-','-');

Open in new window


your output should be:
elsabado-here
This solution (37023947) was really awesome. Thank you so much Ray!