Php regular expressions and preg_replace

Discussion in 'PHP' started by leony, Jun 2, 2008.

  1. #1
    Hi,

    I am trying to implement url rewriting in Apache and my links are as:

    product.php?parent_id=gadgets&product_id=1

    which I want to change as:

    product/80-gb-hard-drive

    To do this I think the first step is to modify the php script and get the items by "title" instead of numbers. But I do not know how to remove the white space in the titles (as well as "&" character) and replace with "-" (dash)

    Someone recommended "preg_replace" but, I did not understand the use of regular expressions. Can anybody help?

    Thanks...
     
    leony, Jun 2, 2008 IP
  2. krakjoe

    krakjoe Well-Known Member

    Messages:
    1,795
    Likes Received:
    141
    Best Answers:
    0
    Trophy Points:
    135
    #2
    sometimes selecting by name isn't possible, some products may have the same name, and some may have the same name once modified to work with rewrite ...

    it would actually be far far simple to have the rewritten url be something like /product/parent/id/name
    so the example posted would then become /product/gadgets/1/80-gb-hard-drive

    they still score the same with SE's and you still have the same data available in REQUEST as you would with the current url ...

    to make a title url friendly

    $title = preg_replace( '~([^a-zA-Z\-])~', '', str_replace( ' ', '-', $title ) );
    PHP:
    this will replace all non alphanumeric characters ( not including - ) with nothing ... and spaces with -

    the rewrite rule you would need would be ...

    
    RewriteEngine On
    RewriteRule ^product/(.[^/]+)/([0-9]+)/(.+)$ product.php?parent_id=$1&product_id=$2
    
    Code (markup):
    This will be much easier to implement as you can use the same select queries to grab data ...
     
    krakjoe, Jun 2, 2008 IP
  3. leony

    leony Peon

    Messages:
    55
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks for the reply Joe. I will follow your recommendation however, how do you add the title in the URL (or is it already there?) as your rewrite rule does not seem to pass the "$title" in the URL. (sorry, my Apache mod rewrite knowledge is not that good)

    Last thing: what does

    '~([^a-zA-Z\-])~'

    mean?
     
    leony, Jun 2, 2008 IP
  4. krakjoe

    krakjoe Well-Known Member

    Messages:
    1,795
    Likes Received:
    141
    Best Answers:
    0
    Trophy Points:
    135
    #4
    ^ negates the character class, it basically means NOT, so anything not in those character classes will b the target for replacement ...

    adding the $title in the url would be down to you, you need to edit whatever code generates the urls ....
     
    krakjoe, Jun 3, 2008 IP