[英]Remove All Kinds of Tabs, White Space, Carriage Return In A String in PHP
我有这样的文本数据:
Learn More
Hide [x]
Colors
Fetching Colors description...
Show more topics
Art exhibitions
Fetching Art exhibitions description...
Abstract art
Fetching Abstract art description...
Representational art
Fetching Representational art description...
我希望能够删除所有回车符,因此它变成这样:
Learn More Hide [x] Colors Fetching Colors description... Show more topics
如何在PHP中做到这一点? 请注意,这些字符串可能是UTF-8字符串,并且我们需要考虑各种制表符,回车符和空格字符。 (我正在考虑在编译器中使用的分词器算法,其中照顾了多个回车符和空格字符。)
您可以使用preg_replace进行尝试:
http://php.net/manual/zh/function.preg-replace.php
$data = preg_replace('/[\s\t\n]{2,}/', ' ', $data);
您可以在以下位置了解有关正则表达式的更多信息: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
您可以在此处进行实时测试: https : //www.phpliveregex.com/
尝试使用preg_replace()将多个空格替换为单个空格,而不是删除制表符( \\t
),空格( \\s
),回车符( \\r
)或换行符( \\n
)
echo preg_replace('/\s+/', ' ', $your_input_string_with_multi_space_goes);
演示: https : //3v4l.org/XMoVr
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.