如何删除不包含在正则表达式中的所有字符

时间:2011-06-28 14:39:16

标签: php

我想删除与指定正则表达式不匹配的所有字符。

例如

$a = "hello my name is ,pate !";

echo notin_replace("[a-zA-Z]","",$a);

hello my name is pate

3 个答案:

答案 0 :(得分:1)

[^a-zA-Z]

在角色类的开头记住carret。这意味着没有。

$a = "hello my name is ,pate !";

echo preg_replace("([^a-zA-Z ])", "", $a);

hello my name is pate

不要忘记为允许的字符添加空格,否则它将被删除。

答案 1 :(得分:1)

preg_replace('/[^a-z ]/i', '', $a); // the /i is for case-insensitive
                                    // put a space inside the expression

答案 2 :(得分:1)

使用preg_replacedocs

<?php
$string = 'hello my name is ,pate !';
// this patter allows all alpha chars and whitespace (tabs, spaces, linebreaks)
$pattern = '/[^a-zA-Z\s]/i';
$replacement = '';
echo preg_replace($pattern, $replacement, $string);
?>

在codepaste.org上试用:http://codepad.org/ZoqcvtIu

相关问题