【问题标题】:I want to remove special symbols, periods, hyphen, underscore & number from a string - PHP我想从字符串中删除特殊符号、句点、连字符、下划线和数字 - PHP
【发布时间】:2012-09-06 05:59:10
【问题描述】:

我的要求是从字符串中删除除下划线以外的所有特殊符号。

我正在使用..

$string = 'text-text_text+text@text(text)text&text.text*text\text/text';
$columnName = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '_', $string);

输出:

text-text_text_text_text(text)text&text.text_text_text_text

但它不会删除句点、与号、括号和破折号。在创建这个正则表达式时,我感到很无助。请帮忙..

【问题讨论】:

  • preg_replace('/[^a-zA-Z0-9]/', '_', $string);
  • 嘿thanx..它工作..添加它作为答案我标记它正确。

标签: php regex string preg-replace


【解决方案1】:

当您想删除除字母、数字和下划线以外的所有字符时,只需使用

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

PREG 函数中的 [^... 之类的表达式意味着您希望保留所有后续字符(因此您的表达式导致 not(!) 删除与号、括号等。

顺便说一句:我省略了表达式中的下划线,因为它会再次被下划线替换,所以不需要在正则表达式中列出它

【讨论】:

    【解决方案2】:

    试试:

    $string = 'text-text_text+text@text(text)text&text.text*text\text/text';
    $columnName = preg_replace('/[-`~!@#$%\^&*()+={}[\]\\\\|;:\'",.><?\/]/', '_', $string);
    

    输出:

    text_text_text_text_text_text_text_text_text_text_text_text
    

    【讨论】:

      猜你喜欢
      • 2011-08-29
      • 1970-01-01
      • 2011-08-16
      • 2016-02-20
      • 2016-09-16
      • 1970-01-01
      • 2011-04-11
      • 2016-01-23
      相关资源
      最近更新 更多