Using String Replace For Hyphens

Hi,

I have am trying to use str_replace to read the spaces in “corner tv units” which in my DB and then replace it with a hyphen so I can run a query such as .com/products/corner-tv-units

I have the below code but I am completely new to string replace. Should I be using $name and $query.

$name = str_replace( " ", "-", <%name%>);
$name = mysql_real_escape_string($_GET['name']);
$query = ("
    SELECT name, product_id, rrp, discount, image_link
    FROM productdbase p
        INNER JOIN furniture_groups f
        ON
            f.long_name = p.furniture_group
    WHERE
        name LIKE '%{$name}%'
    LIMIT 15");

$result = mysql_query($query) or die ("Query: <br>$query<br>Error:<br>".mysql_error());

while ($query_row = mysql_fetch_assoc($result)) { 
  1. Good job using mysql_real_escape_string

  2. You can use $name, but it would be like this $name = str_replace(’ ', ‘-’, $query_row[‘name’]);

  3. You can’t simply re-search something like ‘corner-tv-units’ because you have changed the string, you would need to undo it. Something like str_replace(‘-’,’ ', $name);

  4. If you are absolutely sure you can revert a string replace go ahead with it, otherwise a better solution is to have an extra field that holds the rewritten value, so your query would change from name LIKE ‘…’ to url_name = ‘$name’

What he means with item 4) above is this…

Most commonly, people will store a “slug” (what we call those hyphenated versions of an item name) in a separate field in the table. This way you don’t really have to str_replace anything at all. Just look up the item by it’s slug. That way both name and slug are available simultaneously.

Thanks, I have thought of using slugs. It sounds the easiest method tbh.

Would I add the hyphen at the cron job phase?

Where does a cron job fit into this picture?

How do I create the new slug column?

So I have “corner tv units” in “name” and “corner-tv-units” in “linkname”.

Well, it would happen during the CREATE and UPDATE processes for the corner tv unit, in a CMS or whatever.

How are you putting this data into the DB currently?

Im using a cron job, inserting it from an XML feed.

Ah okay, then yes, you’d do it during the cron job, which is when the insert aka create happens.

Brilliant, thanks.

Now Ive just got to work out how to do that!

Here’s what I use in my framework to convert the names to aliases


		function clean_url($str, $token='-')
		{
			return strtolower(trim(preg_replace(array('~[\\s_]+~', '~[^\\w\\d-]~', '~-{2,}~'), array($token, '', $token), $str), $token));
		}

Thanks, a bit beyond my technical skills tbh . Ive almost completed my site but I paid around $30 for the cron job so I didn’t write it myself.