Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php put a space in front of capitals in a string (Regex)

Tags:

regex

php

I have a number of strings which contain words which are bunched together and I need to seperate them up.

For example ThisWasCool - This Was Cool
MyHomeIsHere - My Home Is Here

Im slowly getting my head around regular expressions and I believe to do this I should use preg_replace. My problem is putting together the expression to find the match.

I have only got this far

   preg_replace('~^[A-Z]~', " ", $string) 

Each string contains a lot of words, but ONLY the first word contains bunched words so using my example above a string would be
"ThisWasCool to visit you again" - "This Was Cool to visit you again"

I have told it to start at the beginning, and look for capitals, but what I dont know how to do is - restrict it only to the first word of each string - how to reuse the capital letter in the replace part after the space

like image 565
Paul M Avatar asked Jul 06 '09 23:07

Paul M


People also ask

How to add space before capital letter in PHP?

Using the PHP preg_replace() function, you can add space in front of uppercase character in a string.


1 Answers

Problem

  1. Your regex '~^[A-Z]~' will match only the first capital letter. Check out Meta Characters in the Pattern Syntax for more information.

  2. Your replacement is a newline character '\n' and not a space.

Solution

Use this code:

$String = 'ThisWasCool'; $Words = preg_replace('/(?<!\ )[A-Z]/', ' $0', $String); 

The (?<!\ ) is an assertion that will make sure we don't add a space before a capital letter that already has a space before it.

like image 124
matpie Avatar answered Sep 19 '22 14:09

matpie