【问题标题】:Reg exp to replace the whole word if any word contains any non alphanumeric character or space如果任何单词包含任何非字母数字字符或空格,则正则表达式替换整个单词
【发布时间】:2010-05-31 00:31:46
【问题描述】:

例如

string = "这是一个很长很长很长的句子";

变成

string = "这是一个很长的句子";

基本上是所有非字母数字单词或删除保持空格在大头钉

有什么想法吗?

【问题讨论】:

    标签: php regex word preg-replace alphanumeric


    【解决方案1】:

    试试这个:

    preg_replace("/(^|\\s)\\S*?[^ a-zA-Z0-9]\\S*?(\\s|$)/", '$1', $string)
    

    【讨论】:

    • 几乎任何时候你使用a-z,你都犯了一个错误。
    • 因为它假定 1960 年代的 7 位 ASCII 世界。
    【解决方案2】:

    我认为这样的事情很直观:

    <?php
    
    $text = "This is a #@^!%$ re@lly long long,long! sentence";
    print preg_replace("/\\w*[^\\w\\s]\\w*\\s*/", "", $text);
    
    ?>
    

    输出是(as seen on ideone.com):

    This is a long sentence
    

    这通过匹配任何\w* 序列后跟[^\w\s](既不是单词字符也不是空格),然后是\w*\s* 的任何序列来工作。与此匹配的任何内容都可以删除,因此将其替换为""

    另见

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多