Skip to content

SEO URL from String

aditya shah edited this page Oct 18, 2016 · 1 revision
//Create SEO URL from String
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);
return $result;
}
$title = "A bunch of ()/*++\'#@$&*^!% invalid URL characters ";
echo(generateSlug($title));
//Output:
//a-bunch-of-invalid-url-characters


class SanitizeUrl {
public static function slug($string, $space="-") {
$string = utf8_encode($string);

if (function_exists('iconv')) {
$string = iconv('UTF-8', 'ASCII//TRANSLIT', $string);
}
$string = preg_replace("/[^a-zA-Z0-9 \-]/", "", $string);
$string = trim(preg_replace("/\\s+/", " ", $string));
$string = strtolower($string);
$string = str_replace(" ", $space, $string);
return $string;
}
}

$title = 'Thi is a test string with some "strange" chars ò à ù...';
echo SanitizeUrl::slug($title);
//this will output:
//thi-is-a-test-string-with-some-strange-chars-o-a-u


//This script redirect not unauthorized users, for example during maintenance.Put ip address of authorized users inside the $admin array.

//admins address
$admins = array('97.23.95.1', '192.168.1.74');
//redirect page for unauthorized users

$page = 'http://www.sitename.com/redirectpage.html';
//////////////////////////////////////////////////////////////////////////
//user ip address
$user = $_SERVER['REMOTE_ADDR'];
//user will be redirect to $page if its ip isn't in the $admin array
//var_dump(array_search($user, $admin));
if(array_search($user, $admins) === FALSE)

{
header('Location: ' . $page);
}
Clone this wiki locally