我有一个 $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);
谢谢
编辑:用测试字符串澄清