简体   繁体   English

PHP:是否存在此代码性能问题? 可以改善吗?

[英]PHP: Has this code performance issues? Can be improved?

I'm trying to make some SEO improvement on my site. 我正在尝试在我的网站上进行一些SEO改进。 I'd like to add some text to my URLs. 我想在URL中添加一些文本。 I'm trying to add information to the URLs. 我正在尝试向URL添加信息。 I get the "product name" (or title) from an item and append it to the URL. 我从项目中获得“产品名称”(或标题),并将其附加到URL。 So, if a "Core 2 Duo 8600 CPU" has id 10, the old URL was: 因此,如果“ Core 2 Duo 8600 CPU”的ID为10,则旧网址为:

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() . 注意:作为URL,我添加了strtolower() Feel free to remove it if you truly want capitals in your URL. 如果您确实要在网址中使用大写字母,请随时将其删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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