【问题标题】:remove htmlentities and leave just text and space using urlencode使用 urlencode 删除 htmlentities 并仅保留文本和空格
【发布时间】:2015-07-27 00:24:34
【问题描述】:

我正在使用以下脚本创建一个 SEO 友好的网址;

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

【问题讨论】:

    标签: php url seo urlencode html-entities


    【解决方案1】:

    一个 preg_replace 就足够了

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

    简单地替换 % 加上任意 2 个字符

    【讨论】:

    • 我试过了,但它没有达到我的要求。它已经停止了转换,但我希望它把它们全部删除,只留下通过加号或减号连接在一起的字母。有点像您在用于此页面的 url 上看到的内容。
    • 已解决。 preg_replace("@%.{2}@", '', urlencode($string);
    【解决方案2】:

    这里迟到的答案

    <?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;
    
    
    ?>
    

    【讨论】:

      猜你喜欢
      • 2016-08-26
      • 2014-08-09
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 2013-06-03
      • 1970-01-01
      • 2023-01-31
      相关资源
      最近更新 更多