• Rewrite URL to dashed string using preg_replace

    Posted by markzero on Saturday, January 29th, 2011

    Did you setup your .htaccess file right? Now you need to generate your links from various parameters. Suppose you have the ‘&’ characters in your string. Also, there are dots, commas, etc. You want to get rid of them all, and just put dashes between words, replaced with spaces. Alright, no problem, but remove spaces on both ends (if any) using trim method:

    <?php $newString = trim($longString); ?>

    Suppose you have some long string, and that should become pretty string. Something like “Stan & Ollie: The Two Clown Angels”, becoming “stan-ollie-the-two-clown-angels”. First, you need to get rid of the ampersand character:

    <?php $newString = preg_replace("/&#?&#91;a-z0-9&#93;+;/i","",$new_str); ?>

    What this regular expression does is, remove everything that begins with ampersand, and ends with ‘;’, having letters in between. Next, we want to remove any character which is not letter:

    <?php $newString = preg_replace("/&#91;^a-zA-Z0-9\s&#93;/", "", $newString); ?>

    What we have now is: “Stan Ollie The Two Clown Angels”. Hardest part is done, next we need to get rid of the spaces:

    <?php $newString = preg_replace("/&#91; &#93;+/", " ", $newString); ?>

    Above piece, will not remove spaces, but will replace several spaces in a row to only one. Like, “Stan   Ollie” becoming “Stan Ollie”. This is not the case here, but is pretty useful. Finally, one-spaced-string replace with dashes:

    <?php $newString = preg_replace("/ /", "-", $newString); ?>

    If you have uppercase characters, we can make it lowercase by simply doing this:

    <?php $newString = strtolower($newString); ?>

    Now we have desired result: “stan-ollie-the-two-clown-angels”. You can wrap all this into one function, and now you have pretty URL translator.

    Posted in: PHP.

    Share this story:

    Leave a Reply