Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making strings "URL safe" [duplicate]

Tags:

string

php

Possible Duplicate:
URL Friendly Username in PHP?

Is there a way to make strings "URL safe" which means replacing whitespaces with hyphens, removing any punctuation and change all capital letters to lowercase?

For example:

"This is a STRING" -› "this-is-a-string"

or

"Hello World!" –› "hello-world"
like image 256
user1706680 Avatar asked Jan 27 '26 04:01

user1706680


2 Answers

You can use preg_replace to replace change those characters.

$safe = preg_replace('/^-+|-+$/', '', strtolower(preg_replace('/[^a-zA-Z0-9]+/', '-', $string)));
like image 160
kmkaplan Avatar answered Jan 29 '26 19:01

kmkaplan


I Often use this function to generate my clean urls and seems to work fine, You could alter it according to your needs but give it a try.

function sanitize($string, $force_lowercase = true, $anal = false) {
    $strip = array("~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "=", "+", "[", "{", "]",
                   "}", "\\", "|", ";", ":", "\"", "'", "‘", "’", "“", "”", "–", "—",
                   "—", "–", ",", "<", ".", ">", "/", "?");
    $clean = trim(str_replace($strip, "", strip_tags($string)));
    $clean = preg_replace('/\s+/', "-", $clean);
    $clean = ($anal) ? preg_replace("/[^a-zA-Z0-9]/", "", $clean) : $clean ;
    return ($force_lowercase) ?
        (function_exists('mb_strtolower')) ?
            mb_strtolower($clean, 'UTF-8') :
            strtolower($clean) :
        $clean;
}
like image 37
0x_Anakin Avatar answered Jan 29 '26 20:01

0x_Anakin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!