0

I'm working with texts that, in some cases, have extra spaces within words. For example:

Marshawn Lynch is amazing. A M A Z I N G!

I want to collapse the "A M A Z I N G" 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.

5
  • Add the code you've tried. Commented Feb 12, 2016 at 13:59
  • Please share what you've tried. Commented Feb 12, 2016 at 13:59
  • You need to provide more samples of what you're trying to detect. For example, you probably don't want to collapse That's a B movie. to get That's aB movie. or even That'saB movie. So, what are you really trying to do? And what have you tried? Commented Feb 12, 2016 at 14:00
  • 2
    How will you differentiate between spaces within words and spaces between words? Are the words with embedded spaces always upper case? Is this a real world problem or an exercise? Commented Feb 12, 2016 at 14:00
  • (?<=[A-Z])(\s)(?=[A-Z]) Commented Feb 12, 2016 at 14:01

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.