Stripping parentheses (and contents) out of URL's

I have a database filled with scientific names that I use as URL’s. They look like this:

Canis lupus
Panthera leo

I can easily use str_replace to replace the space with a hyphen:

Canis-lupus
Panthera-leo

But some URL’s look like this:

Panthera (Felis) sibirica

What’s the best way to strip out the parentheses and their contents and the spaces, replacing them with a hyphen?..

Panthera-sibirica

I’m doing a simple query and displaying URL’s as $URL.

Someone told me to use urlencode, but I don’t understand how it works. Thanks.

using urlencode means that you don’t strip out or change any of the characters - you just encode the ones that are not allowed in a url so they are replaced by character combinations that are allowed and which can convert back to the original values when the url is decoded.

Here is my function for converting strings to SLUGs:

function slug($string){    
    $string = strip_tags(trim($string));
    $string = mb_strtolower($string, 'utf-8');
    $slug = preg_replace ('/[^a-zA-Z0-9\-\/]/u', '-', $string);
    $slug = preg_replace('/([-]+)/i', '-', $slug);
    $slug = trim($slug, '-');
    if (!$slug){ $slug = 'untitled'; }
    return $slug;    
}

Usage:

$slug = slug('Panthera (Felis) sibirica'); //=> panthera-felis-sibirica
2 Likes

Sorry, I guess I didn’t explain clearly. In this case, I don’t want to display panthera-felis-sibirica; I want to strip out the parentheses AND THEIR CONTENTS, so it displays panthera-sibirica. Thanks.

Hmmm…maybe I should look into that. I have lots of URL’s that include apostrophes or accents. So I have type in the code…

’

But I don’t want the code in my URL’s (field Slug), so I have two separate values in my database table:

Richardson’s squirrel
richardsons-squirrel

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.