PHP面试题之驼峰字符串转换成下划线样式例子
自己在看到这个问题的时候,想到的是用ASCII码来处理,没往万能的正则上去想。好吧,下面来看看答案:
答案1:
<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy7630')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy7630>$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.jiaochengji.com
echo strtolower($new) . '<br>';
答案2:
<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy1990')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy1990>echo strtolower(preg_replace('/((?<=[a-z])(?=[A-Z]))/', '_', $str)).'<br>';
那反过来下划线分割字符串转换成驼峰式字符串怎么搞呢
<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy4019')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy4019>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()
}
}
您可能感兴趣的文章:
go练手:简单的单词格式转换工具
PHP实现驼峰命名和下划线命名互转
PHP面试题之驼峰字符串转换成下划线样式例子
php编程之命名规范
PHP变量命名规则详解
php编程之命名规范总结
python标识符是什么
PHP编程之代码命名规范
name是python的标识符吗
Python基础之基本数据类型