Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a nice page title into a valid URL string?

imagine a page Title string in any given language (english, arabic, japanese etc) containing several words in UTF-8. Example:

$stringRAW = "Blues & μπλουζ Bliss's ブルース Schön";

Now this actually needs to be converted into something thats a valid portion of a URL of that page:

$stringURL = "blues-μπλουζ-bliss-ブルース-schön"

just check out this link This works on my server too!

Q1. What characters are allowed as valid URL these days? I remember having seen whol arabic strings sitting on the browser and i tested it on my apache 2 and all worked fine.

I guesse it must become: $stringURL = "blues-blows-bliss-black"

Q2. What existing php functions do you know that encode/convert these UTF-8 strings correctly for URL ripping them off of any invalid chars?

I guesse that at least: 1. spaces should be converted into dashes -
2. delete invalid characters? which are they? @ and '&'?
3. converts all letters to lower case (or are capitcal letters valid in urls?)

Thanks: your suggestions are much appreciated!

like image 832
Sam Avatar asked Mar 07 '11 16:03

Sam


People also ask

How encode URL in PHP?

PHP | urlencode() Function The urlencode() function is an inbuilt function in PHP which is used to encode the url. This function returns a string which consist all non-alphanumeric characters except -_. and replace by the percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs.


1 Answers

this is solution which I use:

$text = 'Nevalidní Český text';
$text = preg_replace('/[^\\pL0-9]+/u', '-', $text);
$text = trim($text, "-");
$text = iconv("utf-8", "us-ascii//TRANSLIT", $text);
$text = preg_replace('/[^-a-z0-9]+/i', '', $text);

Capitals in URL's are not a problem, but if you want the text to be lowercase then simply add $text = strtolower($text); at the end :-).

like image 175
grongor Avatar answered Oct 07 '22 01:10

grongor