[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 616
  • Last Modified:

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!


0
Fernanditos
Asked:
Fernanditos
  • 3
  • 2
  • 2
  • +3
1 Solution
 
xtermCommented:
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

0
 
babuno5Commented:
0
 
xtermCommented:
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.
0
Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

 
dhaval_neesaCommented:
try this code
0
 
dhaval_neesaCommented:

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

0
 
Ray PaseurCommented:
http://www.laprbass.com/RAY_temp_fernanditos.php
<?php // RAY_temp_fernanditos.php
error_reporting(E_ALL);
echo "<pre>";

/* PROBLEM DEFINITION FROM THE POST AT EE
$excluded = "is,the,by,in,a,to"
$PostTitle= "This//:?0¿= is á Tést...---,,,() to create ºúrl"

echo slug($PostTitle);

result: "this-test-create-url"
*/ // END PROBLEM DEFINITION


// EXCLUDED STRINGS
$bad = "is,the,by,in,a,to";

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

// WHAT WE WANT TO CREATE FROM THE INPUT AND THE EXCLUDED STRINGS
$res = "this-test-create-url";

// TEST THE FUNCTION
$new = slug($str);
if ($new = $res) echo "SUCCESS!";

// OUR CUSTOM FUNCTION
function slug($str)
{
    $str = mungstring($str);
    $str = tidystring($str);
    return $str;
}

// A FUNCTION TO RETURN THE WESTERNIZED STRING
function mungString($str, $return='TEXT')
{
    // OUR REPLACEMENT ARRAY (MAY WANT SOME CHANGES HERE)
    static
    $normal
    = array
    ( 'ƒ' => 'f'  // http://en.wikipedia.org/wiki/%C6%91 florin
    , 'Š' => 'S'  // http://en.wikipedia.org/wiki/%C5%A0 S-caron (voiceless postalveolar fricative)
    , 'š' => 's'  // http://en.wikipedia.org/wiki/%C5%A0 s-caron
    , 'Ð' => 'Dj' // http://en.wikipedia.org/wiki/Eth (voiced dental fricative)
    , 'Ž' => 'Z'  // http://en.wikipedia.org/wiki/%C5%BD Z-caron (voiced postalveolar fricative)
    , 'ž' => 'z'  // http://en.wikipedia.org/wiki/%C5%BD z-caron
    , 'À' => 'A'
    , 'Á' => 'A'
    , 'Â' => 'A'
    , 'Ã' => 'A'
    , 'Ä' => 'A'
    , 'Å' => 'A'
    , 'Æ' => 'E'
    , 'Ç' => 'C'
    , 'È' => 'E'
    , 'É' => 'E'
    , 'Ê' => 'E'
    , 'Ë' => 'E'
    , 'Ì' => 'I'
    , 'Í' => 'I'
    , 'Î' => 'I'
    , 'Ï' => 'I'
    , 'Ñ' => 'N'
    , 'Ò' => 'O'
    , 'Ó' => 'O'
    , 'Ô' => 'O'
    , 'Õ' => 'O'
    , 'Ö' => 'O'
    , 'Ø' => 'O'
    , 'Ù' => 'U'
    , 'Ú' => 'U'
    , 'Û' => 'U'
    , 'Ü' => 'U'
    , 'Ý' => 'Y'
    , 'Þ' => 'B'
    , 'ß' => 'Ss'
    , 'à' => 'a'
    , 'á' => 'a'
    , 'â' => 'a'
    , 'ã' => 'a'
    , 'ä' => 'a'
    , 'å' => 'a'
    , 'æ' => 'e'
    , 'ç' => 'c'
    , 'è' => 'e'
    , 'é' => 'e'
    , 'ê' => 'e'
    , 'ë' => 'e'
    , 'ì' => 'i'
    , 'í' => 'i'
    , 'î' => 'i'
    , 'ï' => 'i'
    , 'ð' => 'o'
    , 'ñ' => 'n'
    , 'ò' => 'o'
    , 'ó' => 'o'
    , 'ô' => 'o'
    , 'õ' => 'o'
    , 'ö' => 'o'
    , 'ø' => 'o'
    , 'ù' => 'u'
    , 'ú' => 'u'
    , 'û' => 'u'
    , 'ý' => 'y'
    , 'ý' => 'y'
    , 'þ' => 'b'
    , 'ÿ' => 'y'
    )
    ;
    // RETURN THE "TRANSLATED" TEXT
    if ($return == 'TEXT') return strtr($str, $normal);

    // MIGHT BE USEFUL TO GET THE LIST OF ORIGINAL LETTERS
    return array_keys($normal);
}

// A FUNCTION TO REMOVE CERTAIN WORDS FROM A WESTERNIZED STRING AND INSERT DASHES
function tidyString($str, $bad='is,the,by,in,a,to', $case='i')
{
    // NORMALIZE AND REMOVE NON-ALPHA CHARACTERS
    $str = strtolower($str);
    $str = preg_replace('/[^a-z]/', ' ', $str);

    // REMOVE EACH UNWANTED WORD
    $arr = explode(',', $bad);
    foreach ($arr as $key)
    {
        $rgx
        = '#'              // REGEX DELIMITER
        . '\b'             // WORD BOUNDARY
        . preg_quote($key) // THE ARRAY ELEMENT TO BE REMOVED
        . '\b'             // WORD BOUNDARY
        . '#'              // REGEX DELIMITER
        . $case
        ;
        $str = preg_replace($rgx, NULL, $str);
    }

    // INSERT DASHES IN PLACE OF BLANKS
    $str = preg_replace('#\s+#', '-', $str);
    return $str;
}

Open in new window

0
 
FernanditosAuthor Commented:
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
0
 
FernanditosAuthor Commented:
$bad='is,the,by,in,a,to,http,www,heres'
0
 
re-searcherCommented:
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
0
 
FernanditosAuthor Commented:
This solution (37023947) was really awesome. Thank you so much Ray!
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
  • 2
  • 2
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now