简体   繁体   English

PHP:用正则表达式替换未知字符

[英]PHP: Replace unknown characters with regular expressions

I'm working with texts that, in some cases, have extra spaces within words. 我正在处理在某些情况下单词内有多余空格的文本。 For example: 例如:

Marshawn Lynch is amazing. Marshawn Lynch很棒。 AMAZING! 惊人!

I want to collapse the "AMAZING" part into one word, so that the final result looks like: 我想将“ AMAZING”部分折叠成一个词,以便最终结果如下所示:

Marshawn Lynch is amazing. Marshawn Lynch很棒。 AMAZING! 惊人!

I'm working with PHP, and I'm trying to figure out a way to use preg_replace (maybe there's a better way of doing it?), but I can't figure out where to start. 我正在使用PHP,但是我试图找出一种使用preg_replace的方法(也许有更好的方法吗?),但是我不知道该从哪里开始。

This one looks for whitespaces between two UPPERCASE letters and replaces all occurences: 此代码查找两个大写字母之间的空格并替换所有出现的情况:

$string = "Marshawn Lynch is amazing. A M A Z I N G!";
$regex = "~(?<=[A-Z])\s(?=[A-Z])~";
$string = preg_replace($regex, "", $string);
echo $string;
// output: Marshawn Lynch is amazing. AMAZING!

See a demo on ideone.com . 在ideone.com上查看演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM