我想删除与指定正则表达式不匹配的所有字符。
例如
$a = "hello my name is ,pate !";
echo notin_replace("[a-zA-Z]","",$a);
hello my name is pate
答案 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_replace
(docs)
<?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