Home > Article > Backend Development > PHP interview question: Example of converting camelCase string to underscore style, CamelCase Underline_PHP Tutorial
When I saw this question, I thought of using ASCII code to process it, but I didn’t go into it. Think about the omnipotent rules. Well, let’s take a look at the answer:
Answer 1:
The code is as follows Copy the code
$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) . '
';
Answer 2:
Copy the code as follows
echo strtolower(preg_replace('/((?<=[a-z])(?=[A-Z]))/', '_', $str)).'< br>';
How to reversely divide the string by underline and convert it into a camel (www.111cn.net) peaked string
Copy the code as follows
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
The very simple code is as follows:
preg_replace('/[\s ]/', '_', $content); // Replace spaces, including large spaces. If you have any questions, please feel free to ask~