【问题标题】:Php put a space in front of capitals in a string (Regex) leaving the first occurencePhp 在字符串中的大写字母前面放置一个空格(正则表达式),让第一次出现
【发布时间】:2016-06-09 05:50:34
【问题描述】:

如何在大写字母前添加空格,但保留第一次出现的大写字母

我的字符串是 "MyHomeIsHere" 我希望它是 "My Home Is Here"...但是使用下面的代码我得到 " My Home Is Here" 空格也被添加到 M 之前

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

【问题讨论】:

  • 上面的代码在这里工作正常!
  • 只删除多余的空间:' $0''$0'
  • 你可以使用\B[A-Z]
  • 除了@SebastianProske,这里还有a demo on regex101

标签: php regex


【解决方案1】:

作为答案,使用@SebastianProske 的表达方式并附有解释和指向 ideone 的演示链接:

<?php

$string = 'MyHomeIsHere';
$regex = '~     # delimiters
        \B      # match where \b (a word boundary) does not match
        [A-Z]   # one of A-Z
        ~x';        # free spacing mode for this explanation

$words = preg_replace($regex, ' $0', $string);
echo $words;
# output: My Home Is Here

?>

working on ideone.com

【讨论】:

    【解决方案2】:

    使用正则表达式的解决方案否定后向断言

    $string = 'MyHomeIsHere';
    // (?<!\A) - if a capital's not preceded by 'Start of string'(\A)
    $result = preg_replace("/(?<!\A)[A-Z]+/", ' $0', $string);
    
    var_dump($result);  // "My Home Is Here"
    

    【讨论】:

      【解决方案3】:
      $string = 'I lovePhp because it isAwesome!';
      $regex = '/(?<!^)((?<![[:upper:]])[[:upper:]]|[[:upper:]](?![[:upper:]]))/';
      $string = preg_replace( $regex, ' $1', $string );
      echo $string;
      

      我喜欢 Php,因为它很棒!

      【讨论】:

        【解决方案4】:

        一种完全不同的方法是将字符串转换为数组并单独检查每个字符。不是您正在寻找的答案,但它可能是一个不错的补充。

        $str = 'The ants go marching one by one, hurrah, hurrah.The ants go marching two by two, hurrah, hurrah.The ants go marching three by three,The little one stops to climb a tree.And they all go marching down to the ground.To get out of the rain, boom! boom! boom!';
        
        function addSpace($character, $key) {
            $capitals = range('A', 'Z');
            if (in_array($character, $capitals) && $key != 0) {
                $character = ' '.$character;
            }
            return $character;
        }
        
        $string = implode('', array_map("addSpace", str_split($string), array_keys(str_split($string))));
        

        【讨论】:

          猜你喜欢
          • 2010-11-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-02-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多