2010-01-10 32 views
9
$string = "MaryGoesToSchool"; 

$expectedoutput = "Mary Goes To School"; 
+0

你怎么能指望的 “MaryHasACat” 输出? – 2010-01-10 10:58:39

回答

17

什么是这样的:

$string = "MaryGoesToSchool"; 

$spaced = preg_replace('/([A-Z])/', ' $1', $string); 
var_dump($spaced); 

此:

  • 匹配大写字母
  • 并用空格代替它们中的每一个,什么是匹配


它给出了这个输出:

string ' Mary Goes To School' (length=20) 


然后你可以使用:

$trimmed = trim($spaced); 
var_dump($trimmed); 

要删除开头的空间,它可以帮助您:

string 'Mary Goes To School' (length=19) 
+3

如果字符串已经有空白字符,该怎么办? – Gumbo 2010-01-10 10:56:04

+0

然后'preg_replace('/ *([A-Z])/','$ 1',$ string);'。 – kennytm 2010-01-10 12:20:20

6

尝试这种情况:

$expectedoutput = preg_replace('/(\p{Ll})(\p{Lu})/u', '\1 \2', $string); 

\p{…}符号经由Unicode character properties描述字符; \p{Ll}表示一个小写字母,而\p{Lu}表示一个大写字母。

另一种方法是这样的:

$expectedoutput = preg_replace('/\p{Lu}(?<=\p{L}\p{Lu})/u', ' \0', $string); 

这里,如果它是由另一个字母开头每个大写字母只用空格前缀。所以MaryHasACat也将工作。

1

这里是一个非正则表达式的解决方案,我用于将camelCase字符串格式化为更易读的格式:

<?php 
function formatCamelCase($string) { 
     $output = ""; 
     foreach(str_split($string) as $char) { 
       strtoupper($char) == $char and $output and $output .= " "; 
       $output .= $char; 
     } 
     return $output; 
} 

echo formatCamelCase("MaryGoesToSchool"); // Mary Goes To School 
echo formatCamelCase("MaryHasACat"); // Mary Has A Cat 
?> 
+0

Downvoter - 为什么? – alexn 2010-01-10 11:27:36

0

尝试:

$string = 'MaryGoesToSchool'; 
$nStr = preg_replace_callback('/[A-Z]/', function($matches){ 
    return $matches[0] = ' ' . ucfirst($matches[0]); 
}, $string); 
echo trim($nStr); 
相关问题