删除htmlentities,只留下文本和使用urlencode的空间


remove htmlentities and leave just text and space using urlencode

我正在使用下面的脚本创建一个SEO友好的url;

str_replace("%2F", "+", urlencode(@mynameis 'JaySmoke' and I love (Stackoverflow)))

当我检查生成的地址时,它给了我以下内容;

%40mynameis+%27JaySmoke%27+and+I+love+%28Stackoverflow%29

正如你所看到的,urlencode也编码了htmlentities,我想知道是否有一种方法可以告诉它忽略所有的htmlentities,只编码空格和文本,如;

myname+is+JaySmoke+and+I+love+Stackoverflow

一个preg_replace就足够了

preg_replace("@%.{2}@", '', $string)

替换% +任意两个字符

迟来了

<?php
//$string represents a string text that might contain unwanted characters
$string = $_POST['text-with-all-kind-of-characters'];
//remove all unwanted characters
$res = preg_replace("/[^a-zA-Z0-9 ]/", " ", $string);
//remove extra spaces within the text
$untrimmed = preg_replace('/'s+/', ' ', $res);
//remove extra spaces at ends of string
$trimmed = trim($untrimmed);
//replace all remaining spaces with dash
$urltitle =  str_replace(" ", "+", "$trimmed");
//our final product 
echo $urltitle;

?>