开发者

Using regex to insert a space in a string in php

开发者 https://www.devze.com 2023-04-08 17:37 出处:网络
I have a string that is not properly formed and am attempting to correct it. An example of the string is: -

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

精彩评论

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