Php在一个字符串(Regex)中的大写字母前面加一个空格,留下第一个空格
如何在大写字母前添加空格,但保留第一个大写字母 我的字符串是Php在一个字符串(Regex)中的大写字母前面加一个空格,留下第一个空格,php,regex,Php,Regex,如何在大写字母前添加空格,但保留第一个大写字母 我的字符串是“MyHomeIsHere”我希望它是“我的家在这里”…但是使用下面的代码,我得到的结果是“我的家在这里”在M之前添加了空格 $String = 'ThisWasCool'; $Words = preg_replace('/(?<!\ )[A-Z]/', ' $0', $String); $String='ThisWasCool'; $Words=preg_replace('/(?作为答案,使用@SebastianProske的
“MyHomeIsHere”
我希望它是“我的家在这里”
…但是使用下面的代码,我得到的结果是“我的家在这里”
在M之前添加了空格
$String = 'ThisWasCool';
$Words = preg_replace('/(?<!\ )[A-Z]/', ' $0', $String);
$String='ThisWasCool';
$Words=preg_replace('/(?作为答案,使用@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
?>
请看。一种完全不同的方法是将字符串转换为数组,然后逐个检查每个字符。这不是您要寻找的答案,但可能是一个不错的添加
$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))));
使用regexp负查找断言的解决方案:
$string='MyHomeIsHere';
//(?$string='我喜欢PHP,因为它很可爱!';
$regex='/(?以上代码在这里工作正常!只需删除额外的空间:'$0'
到'$0'
除了@SebastianProske之外,您还可以使用\B[A-Z]
,这里是。
$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"
$string = 'I lovePhp because it isAwesome!';
$regex = '/(?<!^)((?<![[:upper:]])[[:upper:]]|[[:upper:]](?![[:upper:]]))/';
$string = preg_replace( $regex, ' $1', $string );
echo $string;