开发者

Detecting and replacing merged words MyWord to My Word - PHP, regex

I have a function which is detecting and unmerging two words i.e.

HelloWord

after function will become

Hello World

the problem is it will do same to iPhone -> i Phone which is not good, is there a way to replace only if first word is longer than 1

here is开发者_StackOverflow中文版 my current function (regex):

function unseparateWords($string)
{
    $CapRegX = '/(\B[A-Z])(?=[a-z])|(?<=[a-z])([A-Z])/sm';
    $RepStr = ' $1$2';

    return preg_replace($CapRegX,$RepStr,$string);
}

thanks for help.

cheers, /Marcin


You could search for the position between a lowercase and an uppercase character

(?<=\B[a-z])(?=[A-Z])

and replace this "zero-length string" with a space.

(?<=\B[a-z]) # assert that we are right after a lowercase ASCII character
             # unless that character is the start of the current word
(?=[A-Z])    # assert that there is an uppercase ASCII character right ahead

In PHP:

function unseparateWords($string)
{
    return preg_replace('/(?<=\B[a-z])(?=[A-Z])/', ' ', $string);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜