简体   繁体   中英

PHP: Has this code performance issues? Can be improved?

I'm trying to make some SEO improvement on my site. I'd like to add some text to my URLs. I'm trying to add information to the URLs. I get the "product name" (or title) from an item and append it to the URL. So, if a "Core 2 Duo 8600 CPU" has id 10, the old URL was:

example.com/cpu/10

Now, i want to append the product name, so it will be:

example.com/cpu/10/core-2-duo-8600-CPU/

The problem is that i don't want special chars in there, nor accented words (it's a spanish site), so i built this function:

function makeFriendlyURL($string){
        $search = explode(",","ç,æ,œ,á,é,í,ó,ú,à,è,ì,ò,ù,ä,ë,ï,ö,ü,ÿ,â,ê,î,ô,û,å,e,i,ø,u");
        $replace = explode(",","c,ae,oe,a,e,i,o,u,a,e,i,o,u,a,e,i,o,u,y,a,e,i,o,u,a,e,i,o,u");
        $string = str_replace($search, $replace, $string);
        $string = preg_replace("/[^A-Za-z0-9]/"," ",$string);
        $string = preg_replace('/\s+/', '-',trim($string)); 
        return strtolower($string);
    }
makeFriendlyURL('Técnico electricista') //tecnico-electricista  (accented é is replaced with e)
makeFriendlyURL('RAM 1066/1333') // ram-1066-1333 (striped the slash and lowercase "RAM")

Now, do you see any issue? I think it could be improved, but don't know how.

Can this code be improved?

In these situations it's easier to define with what you want than what you don't want, as that is an every changing list.

This is typical code that will create a slug from a title:

// translate accented chars
$search = explode(",","ç,æ,œ,á,é,í,ó,ú,à,è,ì,ò,ù,ä,ë,ï,ö,ü,ÿ,â,ê,î,ô,û,å,e,i,ø,u");
$replace = explode(",","c,ae,oe,a,e,i,o,u,a,e,i,o,u,a,e,i,o,u,y,a,e,i,o,u,a,e,i,o,u");
$string = str_replace($search, $replace, $string);

// create slug by replacing non-alphanumeric chars with a dash
$slug = trim(preg_replace('/[^a-z0-9]+/', '-', strtolower($string)), '-');

Note: as a URL, I've added strtolower() . Feel free to remove it if you truly want capitals in your URL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM