Php put a space in front of capitals in a string (Regex)

前端 未结 4 1142
天涯浪人
天涯浪人 2020-12-03 02:47

I have a number of strings which contain words which are bunched together and I need to seperate them up.

For example ThisWasCool - This Was Cool
MyHomeIsHere -

相关标签:
4条回答
  • 2020-12-03 02:58

    Here's my .02c, this version will only act on the first word, and will preserve sequences of uppercase letters (BMW).

    $str = "CheckOutMyBMW I bought it yesterday";
    $parts = explode(' ', $str);
    $parts[0] = preg_replace('~([a-z])([A-Z])~', '\\1 \\2', $parts[0]);
    $newstr = implode(' ', $parts);
    echo $newstr;
    
    0 讨论(0)
  • 2020-12-03 02:59

    Problem

    1. Your regex '~^[A-Z]~' will match only the first capital letter. Check out Meta Characters in the Pattern Syntax for more information.

    2. Your replacement is a newline character '\n' and not a space.

    Solution

    Use this code:

    $String = 'ThisWasCool';
    $Words = preg_replace('/(?<!\ )[A-Z]/', ' $0', $String);
    

    The (?<!\ ) is an assertion that will make sure we don't add a space before a capital letter that already has a space before it.

    0 讨论(0)
  • 2020-12-03 03:02
    $string = preg_replace('/[A-Z]/', ' $0', $string);
    

    Maybe run the result through ltrim after.

    $string = ltrim(preg_replace('/[A-Z]/', ' $0', $string));
    
    0 讨论(0)
  • 2020-12-03 03:02

    I'm not proficient with regular expression but I would suggest something like the following code:

    $string="ThisWasCool to visit you again";
    $temp = explode(' ',$string, 2);
    $temp[0] = preg_replace('/(.)([A-Z])/','$1 $2', $temp[0]);
    $string = join(' ',$temp);
    

    Looking at SirLancelot code I've got a second solution. Still I prefer the explode solution as you stated that your target it is only the first word of the string.

    $string="ThisWasCool to visit you again";
    $temp = explode(' ',$string, 2);
    $temp[0] = preg_replace('/(?<!^)([A-Z])/',' $0', $temp[0]);
    $string = join(' ',$temp);
    
    0 讨论(0)
提交回复
热议问题