Mar 24

Most of the developers nowadays prefer to rewrite URLs for (Search Engine Optimization)SEO. This code is sample on how to strip symbols from a string.

<?php
function urify($str){
  return str_replace(" ","-",trim(ereg_replace("[^A-Za-z0-9[:space:]]", "", $str)));
}
$string = "I really hate symbol on my URL - 12345 What the !£$%^& ~!@#$%^&*()_+=-[]{}";
echo urify($string);
?>

Output is:
I-really-hate-symbol-on-my-URL–12345-What-the

3 Responses to “Prepare a string to use as URL in PHP”

  1. simplier one:
    preg_replace(‘/[^A-Za-z0-9]/’, ‘-’, $str);

    [Reply]

  2. Nice one, originally, it was something like that, but from our original string, the regex will return:

    I-really-hate-symbol-on-my-URL—12345-What-the—————————

    more regex I guess to strip off multiple spaces before replacing hyphen(“-”) on it. :-D

    [Reply]

  3. Default avatar Joseph says:

    Thanks! I’m now using it for better URL’s on my website!

    [Reply]

Leave a Reply

preload preload preload
Bless CV