开发者

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 functi开发者_Python百科on 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?


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜