2016-11-19 164 views
0

我想將字符串WhatAWonderfulDay變成一個小寫字符串,其中所有的大寫字符前面都帶有下劃線,例如, what_a_wonderful_day。此外,我正在嘗試製作一個反向算法,將a_quick_fox翻譯爲AQuickFox預先在字符串中加下劃線的大寫字母

我正在提供我的實現,但我知道它效率低下。任何方法來簡化這兩個操作?

// 1. WhatAWonderfulDay -> what_a_wonderful_day 

$chars = str_split('WhatAWonderfulDay'); 
$result = ""; 
foreach($chars as $char) { 
    if (ctype_upper($char) && !empty($result)) 
     $result .= "_" 
    $result .= $char; 
} 
echo $result; 

// 2. a_quick_fox => AQuickFox 

$chars = str_split('a_quick_fox'); 

$result = ""; 
$should_make_upper = true; 
foreach($chars as $char) { 
    $result .= (should_make_upper) ? strtoupper($char) : $char; 
    $should_make_upper = false; 
    if ($char == "_") 
     $should_make_upper = true; 
} 
echo $result; 
+1

這最好用正則表達式 – user3791775

+0

做@ user3791775沒錯,但你能詳細說明一下嗎? – Alex

+0

在正則表達式中使用'preg_replace'只選擇大寫字母。你應該檢查[preg_replace](http://php.net/manual/en/function.preg-replace.php)的文檔。 – Marcs

回答

0

下面是一些simpel代碼,將讓你開始:

$string = "AQuickTest"; 

preg_match_all("/[A-Z]/",$string,$matches); 

foreach($matches[0] as $match){ 
    $string = str_replace($match,"_".strtolower($match),$string); 
} 

echo $string; 

結果是:_a_quick_test

0

我使用一些基本的正則表達式的一個有效的解決方案。

爲下劃線添加到某一段文字,可以使用:

function addUnderscores($chars) { 
    return strtolower(preg_replace('/(?<!^)[A-Z]/', '_\\0', $chars)); 
} 

echo addUnderscores('WhatAWonderfulDay'); // Outputs "what_a_wonderful_day" 

要刪除它們,使用

function removeUnderscores($chars) { 
    return preg_replace_callback('/^\w|_(\\w)/', function ($matches) { 
     return strtoupper((sizeof($matches)==2)?$matches[1]:$matches[0]); 
    }, $chars); 
} 

echo removeUnderscores('a_quick_fox'); // Outputs "AQuickFox" 

Try it online

相關問題