How to make URL Safe strings for mod_rewrite using PHP | edrackham




It’s relatively easy to make URL safe strings for use by mod_rewrite. Let’s use the example that you have a form that adds a new blog post to your site. When the user submits this form, you want to generate a URL safe string (based on the title of the blog post) for mod_rewrite to use. This little snippet will show you how this can be achieved in one line of code in PHP.

The following function shows just how easy it is to generate a URL safe string for mod_rewrite. I’ve even included a demo of this code below.

Try it out…

function MakeURLSafeString($string){
    return trim(preg_replace('/[-]{2,}/', '-', preg_replace('/[^a-z0-9]+/', '-', strtolower($_POST['TheString']))), '-');
}

That’s all there is to it! To break it down a little, you could have written it as per the following:

function MakeURLSafeString($string){
    $string = strtolower($string); // Makes everything lowercase (just looks tidier).
    $string = preg_replace('/[^a-z0-9]+/', '-', $string); // Replaces all non-alphanumeric characters with a hyphen.
    $string = preg_replace('/[-]{2,}/', '-', $string); // Replaces one or more occurrences of a hyphen, with a single one.
    $string = trim($string, '-'); // This ensures that our string doesn't start or end with a hyphen.
    return $string;
}


Categories: Mod_Rewrite, PHP, Tools


3 Responses so far.


  1. Joao Lima says:

    please…
    how I can correct this line of script?
    $string = preg_replace (‘ /[^a-z0-9] +/’ , ‘ – ‘ , $string);

    because the accepted language Portuguese-Brazilian caracter in the words, and the line this removing the letter and the accent:
    original example: Lúcio usa clichês e evita até mesmo falar sobre os rivais na Copa

    example script: l-cio-usa-clich-s-e-evita-at-mesmo-falar-sobre-os-rivais-na-copa-1.html

    thank you

  2. Ed says:

    Hello Joao…

    If you modify the line of code to include this:

    $string = preg_replace (‘ /[^a-z0-9úêé] +/’ , ‘ – ‘ , $string);

    That should fix the mod_rewrite for you. You would, of course, have to add in the rest of the native characters for Portuguese-Brazilian, as I have done for the ú, ê and é.

  3. glodakan says:

    thank you very much ed its work for me.. :)

Leave a Reply