user5016229
user5016229

Reputation:

Php put a space in front of capitals in a string (Regex) leaving the first occurence

how do i add space before capital letters but leaving the first occurence of capital letter

my string is "MyHomeIsHere" i want it to be "My Home Is Here"...but with the code below i get as " My Home Is Here" space gets added before M too

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

Upvotes: 1

Views: 696

Answers (4)

Peter
Peter

Reputation: 9123

A totally different approach is to convert your string to an array and check each character individually. Not the answer you are looking for but it might be a nice addition.

$str = 'The ants go marching one by one, hurrah, hurrah.The ants go marching two by two, hurrah, hurrah.The ants go marching three by three,The little one stops to climb a tree.And they all go marching down to the ground.To get out of the rain, boom! boom! boom!';

function addSpace($character, $key) {
    $capitals = range('A', 'Z');
    if (in_array($character, $capitals) && $key != 0) {
        $character = ' '.$character;
    }
    return $character;
}

$string = implode('', array_map("addSpace", str_split($string), array_keys(str_split($string))));

Upvotes: 0

Dillon Burnett
Dillon Burnett

Reputation: 503

$string = 'I lovePhp because it isAwesome!';
$regex = '/(?<!^)((?<![[:upper:]])[[:upper:]]|[[:upper:]](?![[:upper:]]))/';
$string = preg_replace( $regex, ' $1', $string );
echo $string;

I love Php because it is Awesome!

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

The solution using regexp negative lookbehind assertion:

$string = 'MyHomeIsHere';
// (?<!\A) - if a capital's not preceded by 'Start of string'(\A)
$result = preg_replace("/(?<!\A)[A-Z]+/", ' $0', $string);

var_dump($result);  // "My Home Is Here"

Upvotes: 1

Jan
Jan

Reputation: 43169

As an answer using @SebastianProske's expression with explanations and a demo link to ideone:

<?php

$string = 'MyHomeIsHere';
$regex = '~     # delimiters
        \B      # match where \b (a word boundary) does not match
        [A-Z]   # one of A-Z
        ~x';        # free spacing mode for this explanation

$words = preg_replace($regex, ' $0', $string);
echo $words;
# output: My Home Is Here

?>

See it working on ideone.com.

Upvotes: 2

Related Questions