How to generate seo friendly url’s with php?

I want to make http://mysite.com/id255/ to http://mysite.com/gora-beach-inn/.
My php looks like:

$result = mysql_query("
SELECT id, header
FROM Article
"
);


while($data = mysql_fetch_assoc($result)){
mysql_query
("
UPDATE Article
SET seo = '"
.MakeSeo($data['header'])."'
WHERE datum = '"
.$data['datum']."'
"
);
}

//Convert: "åäö" to "aao", "space" to "-", "!?" to "nothing", and all to lower case.
function MakeSeo($string)
{
???
}

Please help me with the MakeSoe function.
I use moderewrite, so I just need help to generate the url, so I can save them in my database.

asked Sep 25 ’09 at 12:00

Johan
2,41493358
1 
Take a look at the related questions on the right side. – Gumbo Sep 25 ’09 at 12:01

up vote 4 down vote accepted
To just answer your requirement .. here you go ..

function makeSeo($text, $limit=75)
{
// replace non letter or digits by -
$text
= preg_replace('~[^\pLd]+~u', '-', $text);

// trim
$text
= trim($text, '-');

// lowercase
$text
= strtolower($text);

// remove unwanted characters
$text
= preg_replace('~[^-w]+~', '', $text);

if(strlen($text) > 70) {
$text
= substr($text, 0, 70);
}

if (empty($text))
{
//return 'n-a';
return time();
}

return $text;
}

You can add more filters to clean the url and may be you add some more stuff to get that url a unique.
Note: I am not saying that adding url to the database is the best way. You could achieve the same sort of functionality using other techniques, for example, mod_rewrite.

answered Sep 25 ’09 at 12:11

HappyApe
4,37572246
Thanks, works fine, except for åäö, the script generates “1253883725” if $text contains åäö. – Johan Sep 25 ’09 at 13:06
hmm .. may be this is because it converts anything other than a-z,A-z,0-9 to empty. YOu can try remove 2nd preg_match (//remove unwanted characters and test) – HappyApe Sep 25 ’09 at 14:47

2 Responses

Leave a Reply

Your email address will not be published. Required fields are marked *