KryptoniteDove
KryptoniteDove

Reputation: 1268

Using regex to insert a space in a string in php

I have a string that is not properly formed and am attempting to correct it. An example of the string is: -

A Someone(US)B Nobody(US)

I am attempting to correct it to: -

A Someone(US) B Nobody(US)

I am using the below code to match ")" followed by a capital letter and using php's preg_replace function to do the match and add the space. However I'm completely rubbish at regex and cannot get the space added in the correct place.

$regex = "([\)][A-Z])";
$replacement = ") $0";
    $str = preg_replace($regex, $replacement, $output);

Can anyone suggest a better method? I realise the space is not adding correclty because $0 contains the data I am matching, is there a way to manipulate $0?

Upvotes: 2

Views: 1774

Answers (2)

Kent
Kent

Reputation: 195059

how about regex="(?<=\))[A-Z]"
and replacement=" $0"

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

$str = preg_replace('/(?<=\))(?=\p{Lu})/u', ' ', $output);

inserts a space between a closing parenthesis (\)) and an uppercase letter (\p{Lu}). You don't need $0 (or $1 etc.) at all since you're just inserting something at a position between two characters, and this regex matches exactly this (zero-width) position. Check out lookaround assertions.

Upvotes: 2

Related Questions