如何删除字符串中的所有标点只是获取PHP中的空格分隔的单词

时间:2012-05-30 05:39:41

标签: php string

我想删除字符串中的任何类型的特殊字符:

This is, ,,, *&% a ::; demo +  String.  +
Need to**@!/// format:::::
 !!! this.`

需要输出:

This is a demo String Need to format this

如何使用REGEX执行此操作?

4 个答案:

答案 0 :(得分:14)

检查非数字,非字母字符的重复实例,并用空格重复:

# string(41) "This is a demo String Need to format this"
$str = trim( preg_replace( "/[^0-9a-z]+/i", " ", $str ) );

演示:http://codepad.org/hXu6skTc

/       # Denotes start of pattern
[       # Denotes start of character class
 ^      # Not, or negative
 0-9    # Numbers 0 through 9 (Or, "Not a number" because of ^
 a-z    # Letters a through z (Or, "Not a letter or number" because of ^0-9
]       # Denotes end of character class
+       # Matches 1 or more instances of the character class match
/       # Denotes end of pattern
i       # Case-insensitive, a-z also means A-Z

答案 1 :(得分:4)

使用:

preg_replace('#[^a-zA-Z0-9 ]#', '', $yourString);

如果字符不是字母,数字或空格,则用空字符串替换。

示例:

$yourString = 'This is, ,,, *&% a ::; demo +  String.  + Need to**@!/// format::::: !!! this.`';
$newStr = preg_replace('#[^a-zA-Z0-9 ]#', '', $yourString);
echo $newStr;

<强>结果:

This is a demo String Need to format this

因此,如果您想将更多字符放入其中,可以允许更多字符:

[^a-zA-Z0-9 ]

注意:另外,如果你不想在单词之间允许多个空格(虽然在浏览器中输出时不会显示它们),你需要使用它来代替:

preg_replace('#[^a-zA-Z0-9]+#', ' ', $yourString);

答案 2 :(得分:2)

$string = preg_replace('/[^a-z]+/i', ' ', $string);

您可能还希望允许角色类中的'don't之类的连词转换为don t

$string = preg_replace('/[^a-z\']+/i', ' ', $string);

您可能还想在之后修剪它以删除前导和尾随空格:

$string = trim(preg_replace('/[^a-z\']+/i', ' ', $string));

答案 3 :(得分:2)

echo preg_replace('/[^a-z]+/i', ' ', $str); 
// This is a demo String Need to format this