简体   繁体   中英

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. AMAZING!

I want to collapse the "AMAZING" part into one word, so that the final result looks like:

Marshawn Lynch is amazing. 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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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