Web Hosting Talk







View Full Version : Fnction to make a URL friendly title?


yegorpb
05-05-2007, 04:57 PM
Does anyone already have a pre-made function to turn a title like the following:

Bob's table isn't green, is it?

into something like

bobs_table_isnt_green_is_it

Would be much appriciated

Engelmacher
05-05-2007, 05:04 PM
Between str_replace and preg_replace you should be able to get something going pretty quickly there.

yegorpb
05-05-2007, 09:12 PM
I know, but Im not a pro when it comes to those areas to php. I was hoping for an already made function that does this effectively and cleanly.

azizny
05-05-2007, 10:22 PM
$remove_chars = array('"',"'",'?');
$replace_chars = array(' ');

$url = "Bob's table isn't green, is it?";

foreach($remove_chars as $do){
$url = str_replace($do,'',$url);
}
foreach($replace_chars as $do){
$url = str_replace($do,'_',$url);
}



Peace,

Jatinder
05-06-2007, 09:05 AM
azizny you don't need to use the foreach loops. str_replace can accept arrays as parameters.

So, you can just use:


$remove_chars = array('"', "'", '?');
$replace_chars = array(' ');

$url = "Bob's table isn't green, is it?";

$url = str_replace($remove_chars, '', $url);

$url = str_replace($replace_chars, '_', $url);

mitchlrm
05-07-2007, 07:13 AM
If you just need it to work in a URL then how about just:
$url = "Bob's table isn't green, is it?";
$urlout = urlencode($url);

avocado
05-07-2007, 05:38 PM
$new_text = preg_replace('/[^a-zA-Z0-9]+/','_',$text_to_convert);

or, if you want to use hyphens, which are more SEO-friendly:

$new_text = preg_replace('/[^a-zA-Z0-9]+/','-',$text_to_convert);

yegorpb
05-07-2007, 11:31 PM
Hyphens are better for SEO? I would never have imagined.

Thanks for the help

ProperHost
05-08-2007, 07:17 AM
Search engines (at least Google) treat hyphens in the same way as spaces, so if you have a page named my-best-page.html it would have equally chance of showing up in the results regardless if the user searched for "my best page" or "my-best-page".

If the file was named my_best_page.html you will have to actually include the underscores in the search for it to show up. Oh well, I guess you got the idea :)

ak7861
05-11-2007, 12:17 AM
Hyphens are better for SEO? I would never have imagined.

Thanks for the help
Hyphens are better for SEO because they are used more often than underscores and thus in search engines you would get more results if you searched the keyword with a hyphen. I personally use underscores since some of my titles require a hyphen by proper grammar.