Php在字符串(正则表达式)中放置一个空格,留下第一个出现的空格

时间:2016-06-09 05:50:34

标签: php regex

如何在大写字母之前添加空格,但是首次出现大写字母

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

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

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

使用regexp 负面后瞻断言的解决方案

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

答案 2 :(得分:0)

完全不同的方法是将字符串转换为数组并单独检查每个字符。不是你想要的答案,但它可能是一个很好的补充。

$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))));

答案 3 :(得分:0)

$string = 'I lovePhp because it isAwesome!';
$regex = '/(?<!^)((?<![[:upper:]])[[:upper:]]|[[:upper:]](?![[:upper:]]))/';
$string = preg_replace( $regex, ' $1', $string );
echo $string;

我喜欢Php,因为它太棒了!