Detecting and replacing merged words MyWord to My

2019-08-06 05:31发布

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

1条回答
Juvenile、少年°
2楼-- · 2019-08-06 06:14

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);
}
查看更多
登录 后发表回答