【问题标题】:remove all the special character In start of a string using PHP使用PHP删除字符串开头的所有特殊字符
【发布时间】:2013-03-25 10:15:19
【问题描述】:

如何使用 PHP 删除字符串开头(首字母应为字母数字)中的所有特殊字符?请

$String = "+&,Hello+{+ +$world";

删除字符串开头的所有特殊字符后

字符串应该变成“Hello+{+ +$world”

帮帮我。

【问题讨论】:

  • 请告诉我匹配的 URL 吗?

标签: php regex string


【解决方案1】:

这将替换开头的所有非字母数字:

preg_replace('/^([^a-zA-Z0-9])*/', '', $string);

更新:

如果您需要修剪字符串开头和结尾的非字母数字字符,请使用:

<?php

$string = "++&5Hello ++f s world6f++&ht6__)  ";

echo preg_replace('/(^([^a-zA-Z0-9])*|([^a-zA-Z0-9])*$)/', '', $string);

【讨论】:

  • 错误显示如下警告:preg_replace() [function.preg-replace]:编译失败:在 C:\xampp\htdocs\test.php 第 5 行的偏移 16 处没有重复内容跨度>
  • 告诉我如何使用 PHP 删除每个字符串开头和结尾的所有特殊字符?请。
  • @soavahaf 已更新答案以回答您的请求。我必须指出,尽管您的原始问题明确要求标题中字符串的开头。
  • 哦,我知道。谢谢你的回答。
【解决方案2】:

尝试使用trim 了解更多信息,请参阅http://php.net/manual/en/function.trim.php

要从字符串开头删除,您可以使用ltrim http://www.php.net/manual/en/function.ltrim.php

要从字符串末尾删除,您可以使用rtrim http://www.php.net/manual/en/function.rtrim.php

您的示例代码

$String = "+&,Hello+{+ +$world";
echo ltrim($String,"&+,");

您可以在 ltrim 中添加更多字符以从字符串的第一个中删除

【讨论】:

    【解决方案3】:
    <?php
    function string_cleaner($result)
    {
        $result = strip_tags($result);
        $result = preg_replace('/[^\da-z]/i', ' ', $result);
        $result = preg_replace('/&.+?;/', '', $result); 
        $result = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', ' ', $result);
        $result = preg_replace('|-+|', ' ', $result);
        $result = preg_replace('/_+/', ' ', $result);
        $result = preg_replace('/&#?[a-z0-9]+;/i','',$result);
        $result = preg_replace('/[^%A-Za-z0-9 _-]/', ' ', $result);
        $result = preg_replace('/^\W+|\W+$/', '', $result);
        $result = preg_replace('/\s+/', ' ', $result);
        $result = trim($result, ' ');
        return $result;
    }
    ?>
    
    <?php
    echo string_cleaner($content);
    ?>
    

    【讨论】:

    • 试试这个 $result = preg_replace('/^\W+|\W+$/', '', $result);
    • 这段代码到底在做什么?为什么需要这么多不同的正则表达式?
    • @Devan 您在 cmets 中的正则表达式不会替换下划线。
    • 你可以添加这一行 $result = str_replace('_', ' ', $result);或者使用这个 $result = preg_replace('/_+/', ' ', $result);
    【解决方案4】:

    试试这个

       preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $String);
    

    【讨论】:

      【解决方案5】:

      使用 trim - 这是一个内置功能: http://php.net/manual/en/function.trim.php

      【讨论】:

        【解决方案6】:

        我认为使用 ltrim 会更有用,因为您想在字符串的开头删除:http://www.php.net/manual/en/function.ltrim.php

        【讨论】:

        • 你能分享一下你要找的例子吗?
        • $String = "+&,Hello+{+ +$world";从字符串开头删除特殊字符后,字符串将打印为 "Hello+{+ +$world"
        • 如果你有特殊字符的列表,你可以调用 $trimmed = ltrim($text, "{your special Charter}");循环运行所有特殊字符。记得使用 $trimmed 变量传递到下一个循环。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-16
        • 2011-11-13
        • 1970-01-01
        • 2014-02-22
        • 1970-01-01
        • 2011-08-29
        相关资源
        最近更新 更多