generate seo friendly url from string in php

Solutions on MaxInterview for generate seo friendly url from string in php by the best coders in the world

showing results for - "generate seo friendly url from string in php"
Kahina
18 Sep 2020
1<?php
2/**
3* Generate a URL friendly "slug" from a given string.
4*
5* @param  string  $title
6* @param  string  $separator
7* @return string
8*/
9function slug($title, $separator = '-')
10{
11    // convert String to Utf-8 Ascii
12    $title = iconv(mb_detect_encoding($title, mb_detect_order(), true), "UTF-8", $title);
13 
14    // Convert all dashes/underscores into separator
15    $flip = $separator == '-' ? '_' : '-';
16 
17    $title = preg_replace('!['.preg_quote($flip).']+!u', $separator, $title);
18 
19    // Remove all characters that are not the separator, letters, numbers, or whitespace.
20    $title = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', mb_strtolower($title));
21 
22    // Replace all separator characters and whitespace by a single separator
23    $title = preg_replace('!['.preg_quote($separator).'\s]+!u', $separator, $title);
24 
25    return trim($title, $separator);
26}
27
28  $string = "She (sells) seA shells at -the SEA shore?";
29  $slug = slug($string);
30  echo $slug;
31  ?>
32    
33    //Output is: she-sells-sea-shells-at-the-sea-shore