如何删除没有特殊字符的空格和数字?

时间:2015-10-21 10:06:57

标签: php regex preg-replace

我有像这种模式的字符串,我想

income_statement @其他收入(少数股息)@ 9

  • 删除数字

  • 删除除@

  • 之外的特殊字符
  • 用下划线替换空格

我做了类似的事情,但它还没有成功

$spaces = str_replace(' ', '_', $key);
 echo  $numbers = preg_replace("/[^a-zA-Z]/", "_", $spaces);

4 个答案:

答案 0 :(得分:1)

<?php
// this should work and replace all spaces with underscores
$spaces = str_replace(' ', '_', $key);

// you have to add the @ and the underscores in your expression
// and replace it with an empty string
echo  $numbers = preg_replace('/[^a-zA-Z@_]/', '', $spaces);

答案 1 :(得分:1)

您可以使用两个 preg_replace 和一个 str_replace 完成此操作:

$str = 'income_statement@Other Income (Minority Interest)@9';
 // Change space to underscore
 $str = str_replace(' ','_',$str);
 // Remove all numbers
$str = preg_replace('/[\d]+/','',$str);
// Remove all characters except words and @ in UTF-8 mode
$str = preg_replace('/[^\w@]+/u','',$str);

// Print it out
echo $str;

答案 2 :(得分:1)

第一步(删除数字,每个非字母,请注意,这包括下划线_,但不是简单的空格)

$re = "/(?:[^a-z@ ]|\d)/i";
$str = "income_statement@Other Income (Minority Interest)@9"; 
$subst = ""; 

$result = preg_replace($re, $subst, $str);

输出:

incomestatement@Other Income Minority Interest@

第二步(带有下划线的子空格_

$re = "/\s+/";
$str = "incomestatement@Other Income Minority Interest@";
$subst = "_"; 

$result = preg_replace($re, $subst, $str);

输出:

incomestatement@Other_Income_Minority_Interest@

紧凑版本

$str = "income_statement@Other Income (Minority Interest)@9";
$stripped = preg_replace("/(?:[^a-z@ ]|\d)/i", "", $str);
$result = preg_replace("/\s+/", "_", $stripped);

答案 3 :(得分:1)

$data = preg_replace("/[^a-zA-Z@ ]+/", '', $data); // remove all except letters and @ (if you want keep \n and \t just add it in pattern)
$data = str_replace(' ', '_', $data);