我有一个$text,可以去掉所有非字母数字字符,用单个空格替换多个空格和换行符,并消除开始和结束空格。
到目前为止,这是我的解决方案。
$text = '
some- text!!
for testing?
'; // $text to format
//strip off all non-alphanumeric chars
$text = preg_replace("/[^a-zA-Z0-9\s]/", "", $text);
//Replace multiple white spaces by single space
$text = preg_replace('/\s+/', ' ', $text);
//eliminate beginning and ending space
$finalText = trim($text);
/* result: $finalText ="some text for testing";
without non-alphanumeric chars, newline, extra spaces and trim()med */有没有可能在一个正则表达式中组合/实现所有这些?因为我只需要一行代码就可以得到想要的结果,如下所示
$finalText = preg_replace(some_reg_expression, $replaceby, $text);谢谢
编辑:使用测试字符串进行澄清
发布于 2012-06-20 15:16:58
你当然可以。这很简单。
re将如下所示:
((?<= )\s*)|[^a-zA-Z0-9\s]|(\s*$)|(^\s*)我手头没有PHP,我使用了Perl (只是为了测试re并展示它的工作)(你可以使用我的代码here):
$ cat test.txt
a b c d
a b c e f g fff f
$ cat 1.pl
while(<>) {
s/((?<= )\s*)|[^a-zA-Z0-9\s]|(\s*$)|(^\s*)//g;
print $_,"\n";
}
$ cat test.txt | perl 1.pl
a b c d
a b c e f g fff f对于PHP,它将是相同的。
RE的作用是什么?
((?<= )\s*) # all spaces that have at least one space before them
|
[^a-zA-Z0-9\s] # all non-alphanumeric characters
|
(\s*$) # all spaces at the end of string
|
(^\s*) # all spaces at the beginning of string这里唯一棘手的部分是((?<= )\s*),lookbehind断言。当且仅当空格的子字符串之前有空格时,才能删除空格。
当你想知道前视/后视断言是如何工作的,请看一下http://www.regular-expressions.info/lookaround.html。
来自discussion的更新
当使用$text ='some ? ! ? text';时会发生什么?则生成的字符串在"some“和"text”之间包含多个空格。
要解决这个问题并不容易,因为人们需要可变长度的正向回溯断言,而这在目前是不可能的。人们不能简单地检查空格,因为它可能发生,所以它不是空格而是非字母数字字符,并且无论如何都会被移除(例如:在" !"中,"!"符号将被移除,但RE对此一无所知;一个人需要类似(?<=[^a-zA-Z0-9\s]* )\s*的东西,但不幸的是,这将不起作用,因为不支持lookbehind可变长度断言。
发布于 2012-06-20 15:01:54
我不认为您可以用一个正则表达式来实现这一点。您基本上需要固定在if else条件中,仅通过正则表达式是不可能的。
您基本上需要一个regex来删除非字母数字,另一个regex来折叠空格,这基本上就是您已经在做的事情。
发布于 2012-06-20 15:05:08
如果这就是你要找的-请勾选此项
$patterns = array ('/[^a-zA-Z0-9\s]/','/\s+/');
$replace = array ("", ' ');
trim( preg_replace($patterns, $replace, $text) );MAy它可能需要一些修改,如果这是你想做的事情,请让我知道??
https://stackoverflow.com/questions/11114307
复制相似问题