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!
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!
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
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;
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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
@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¿?¿)()/&%$
Result: -elsabado-here-
How to remove the "-" from both cases ?
Thank you so much1
ASKER
$bad='is,the,by,in,a,to,ht tp,www,her es'
Fernanditos
you can remove dash from both case with following function:
your output should be:
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)));
}
echo trimString('-elsabado-here-','-');
your output should be:
elsabado-here
ASKER
This solution (37023947) was really awesome. Thank you so much Ray!
Open in new window