简体   繁体   English

编码SEO友好的URL

[英]Encoding SEO friendly URL

I am trying to encode a phrase in order to pass it inside a URL. 我正在尝试对短语进行编码,以便将其传递到URL中。 Currently it works fine with basic words, where spaces are replaces with dashes. 目前,它可以与基本单词配合使用,其中的空格用短划线代替。

<a href="./'.str_replace(' ', '-', preg_replace("/[^A-Za-z0-9- ]/", '', $phrase)).'">

It produces something like: 它产生类似:

/this-is-my-phase

On the page that this URL takes me I am able to replace the dashes with spaces and query my db for this phrase. 在此URL带我的页面上,我能够将破折号替换为空格,并在数据库中查询该短语。

The problem I have is if the phrase contains apostrophe. 我的问题是该短语是否包含撇号。 My current script removes it. 我当前的脚本将其删除。 Is there any way to preserve it or replace with some URL-friendly character to accommodate something like? 有什么方法可以保留它,或替换为一些URL友好字符以容纳类似内容吗?

this is bob's page

There is a PHP standard library function urlencode() to encode non-alphanumeric characters with %Xxx where xx is the hex value of the character. 有一个PHP标准库函数urlencode()%Xxx编码非字母数字字符,其中xx是字符的十六进制值。

If the limitations of that conversion (&, ©, £, etc.), are not acceptable, see rawurlencode() . 如果该转换的限制(&,©,£等)不可接受,请参见rawurlencode()

如果要允许其他字符,则必须将其添加到此部分: ^A-Za-z0-9-因此,例如,如果您希望允许'则正则表达式将为[^A-Za-z0-9-' ]

If you only need to replace all the apostrophes ( ' ), then you can replace it with the URL-encoded character %27 : 如果只需要替换所有的撇号( ' ),则可以将其替换为URL编码字符%27

str_replace("'", "%20", $url);

EDIT 编辑

If you want to replace all URL-non-safe character, use a built-in function like in @wallyk's answer. 如果要替换所有URL非安全字符,请使用内置函数,例如@wallyk的答案。 It's much simpler. 这要简单得多。

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

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