我有一个$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);
谢谢
编辑:用测试字符串澄清
当然可以。这很容易。
re将如下所示:
((?<= )'s*)|[^a-zA-Z0-9's]|('s*$)|(^'s*)
我手头没有PHP,我使用了Perl(只是为了测试re并证明它有效)(你可以在这里玩我的代码):
$ 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*)
,后看断言。当且仅当空格的子字符串前面有空格时,才删除空格。
当您想知道前瞻/后瞻断言的工作原理时,请查看 http://www.regular-expressions.info/lookaround.html。
讨论更新:
$text ='some ? ! ? text';
时会发生什么?然后,生成的字符串在"一些"和"文本"之间包含多个空格。
解决这个问题并不容易,因为人们需要具有可变长度的正面回溯断言,而目前这是不可能的。不能简单地检查空格,因为它可能发生,因此它不是空格而是非字母数字字符,并且无论如何都会被删除(例如:" !"
"!"
符号将被删除,但 RE 对此一无所知;需要类似 (?<=[^a-zA-Z0-9's]* )'s*
的东西,但不幸的是,这不起作用,因为 PCRE 不支持后视可变长度断言。
我不认为你可以用一个正则表达式来实现这一点。您基本上需要坚持if else
条件,这仅通过正则表达式是不可能的。
删除非字母数字数字,另一个正则表达式来折叠空格,这基本上是您已经在做的事情。
检查一下这是否是您要查找的内容---
$patterns = array ('/[^a-zA-Z0-9's]/','/'s+/');
$replace = array ("", ' ');
trim( preg_replace($patterns, $replace, $text) );
我可能需要一些修改,只要让我知道这是否是你想做的事情??
为了您自己的理智,您需要保留以后仍然可以理解和编辑的正则表达式:)
$text = preg_replace(array(
"/[^a-zA-Z0-9's]/", // remove all non-space, non-alphanumeric characters
'/'s{2,}/', // replace multiple white space occurrences with single
), array(
'',
' ',
), trim($originalText));
$text =~ s/([^a-zA-Z0-9's].*?)//g;
不必比这更难。