2

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?

2
  • $0 is capture group zero which is ([\)][A-Z]), just move the paranthesis like this [\)]([A-Z]) and use $1 I think. Commented Sep 24, 2011 at 20:15
  • I don't think there is a capture group $1, I've tried this and it chops off the capital letter, so produces an output of A Someone(US) Nobody(US). Commented Sep 24, 2011 at 20:28

2 Answers 2

2
$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.

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

2 Comments

How would you adapt this to lowercase letter preceding a capital letter again no space? I tried /(?<=))(?=\p{Lu})/u but no joy..
Do you mean "insert a space between a lowercase and an uppercase letter"? $str = preg_replace('/(?<=\p{Ll})(?=\p{Lu})/u', ' ', $output);
0

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

1 Comment

This regex causes an Unknown modifier '[' error when used with preg_replace.

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.