Forum Moderators: coopster

Message Too Old, No Replies

Replace special chars by underscores

Any help appreciated by converting strings to be used in URLs

         

thijsnetwork

7:29 pm on Jun 4, 2004 (gmt 0)

10+ Year Member



Hi,

My website is written in PHP, and I want that the news-articles can be accessed by friendly URLs, for search engine optimization. I'd like to have the title of a news-message to be converted to become a valid url:

for example:

"Hi, welcome at the site" to be converted in "hi__welcome_at_the_site"

How can I reach this using PHP?

Thus only a-zA-Z0-9_ may be used in the output, the input can contain anything like "?,#$%& etc"

NameNick

7:54 pm on Jun 4, 2004 (gmt 0)

10+ Year Member



thijsnetwork,

You can use these lines of code:

$old_pattern = array("/[^a-zA-Z0-9]/", "/_+/", "/_$/");
$new_pattern = array("_", "_", "");

$file_name = strtolower(preg_replace($old_pattern, $new_pattern , $text_title));

All characters but a to z, A to z and 0 to 9 are replaced by an underscore. Multiple connected underscores are reduced to a single underscore and trailing underscores are removed.

Hope that helps.

NN

thijsnetwork

2:02 pm on Jun 5, 2004 (gmt 0)

10+ Year Member



Wow, it works great, thanks!