检测并替换合并的单词MyWord到我的Word-PHP、regex

2022-03-22 00:00:00 regex php preg-replace

我有一个检测并解合并两个单词的功能,即

HelloWord

After函数将变为

Hello World

问题是iPhone也会这样->iPhone不太好,有没有办法只有在第一个单词超过1的情况下才能替换

以下是我当前的函数(Regex):

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

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

感谢您的帮助。

干杯, /Marcin


解决方案

您可以搜索介于小写和大写字符之间的位置

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

并将此"零长度字符串"替换为空格。

(?<=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

在PHP中:

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

相关文章