自己在看到這個問題的時候,想到的是用ASCII碼來處理,沒往萬能的正則上去想。好吧,下面來看看答案:
答案1:
代碼如下 復制代碼
$str = 'OpenAPI';
$length = mb_strlen($str);
$new = '';
for($i = 0; $i < $length; $i++)
{
$num = ord($str[$i]);
$pre = ord($str[$i - 1]);
$new .= ($i != 0 && ($num >= 65 && $num <= 90) && ($pre >= 97 && $pre <= 122)) ? "_{$str[$i]}" : $str[$i];
} www.111cn.net
echo strtolower($new) . '<br>';
答案2:
代碼如下 復制代碼
echo strtolower(preg_replace('/((?<=[a-z])(?=[A-Z]))/', '_', $str)).'<br>';
那反過來下劃線分割字符串轉換成駝(www.111cn.net)峰式字符串怎麼搞呢
代碼如下 復制代碼
f = new File("d:/temp/t.txt")
if(f.exists()){
f.eachLine{ line->
line = line.trim()
String[] elems = line.split('_')
for(int i = 0; i < elems.length; i++){
elems[i] = elems[i].toLowerCase()
if(i != 0){
String elem = elems[i]
char first = elem[0] as char
elems[i] = "" + (char)(first - 32) + elem.substring(1)
}
}
println elems.join()
}
}
from:http://www.111cn.net/phper/php-cy/59093.htm
public class transform {public static String trans(String str){List record =new ArrayList();for(int i=0;i<str.length();i++){char tmp =str.charAt(i);if((tmp<='Z')&&(tmp>='A')){record.add(i);//記錄每個大寫字母的位置}}record.remove(0);//第一個不需加下劃線str= str.toLowerCase();char[] charofstr = str.toCharArray();String[] t =new String[record.size()];for(int i=0;i<record.size();i++){t[i]="_"+charofstr[(int)record.get(i)];//加“_”}String result ="";int flag=0;for(int i=0;i<str.length();i++){if((flag<record.size())&&(i==(int)record.get(flag))){result+=t[flag];flag++;}elseresult+=charofstr[i];}return result;}public static void main(String [] args){String hh = "HelloWolrd";System.out.println(trans(hh));}}
很簡單代碼如下:
preg_replace('/[\s ]/', '_', $content); // 替換空格,包括大空格如果有疑問,歡迎追問~