一道PHP面试题的思考
题目是这样的:写一个php函数,将’9123456789′,转话成’9,123,456,789’的形式。
解法1:
function changeStr($str) { return number_format($str, 0, ',', ','); }
解法2:
function changeStr($str) { return preg_replace('/\B(?=(\d{3})+$)/i', ',', $str); }
解法3:
function changeStr($str) { return preg_replace('/\B(\d{3})/i', ',$1', $str); }
解法4:
function changeStr($str) { $ret = ''; $len = strlen($str); $left = $len%3; for ($i=0; $i<$len; $i++) { if ($i%3 == $left && $i !==0) { $ret .=','; } $ret .= $str[$i]; } return $ret; }
除了php提供的number_format外,使用正则替换是最简洁的方法了,当然,在使用number_format前,需要确认提供的字符串是否为数字串。
正则表达式在处理字符串问题时,是一个强有力的工具,下面再看些例子。
例1:实现一个unix样式的命令行过滤器,将段落开始部分的大写字母转换为小写。
<?php $fp = fopen("php://stdin", "r") or die("can't read stdin"); while (!feof($fp)) { $line = fgets($fp); $line = preg_replace_callback( '/\s*\w/', function ($matches) { return strtolower($matches[0]); }, $line ); echo $line; } fclose($fp);
例2:BB码转html
<?php $input = "plain [indent] deep [indent] deeper [/indent] deep [/indent] plain"; function parseTagsRecursive($input) { $regex = '#\[indent]((?:[^[]|\[(?!/?indent])|(?R))+)\[/indent]#'; if (is_array($input)) { $input = '<div style="margin-left: 10px">'.$input[1].'</div>'; } return preg_replace_callback($regex, 'parseTagsRecursive', $input); } $output = parseTagsRecursive($input); echo $output;
码字很辛苦,转载请注明来自胡伟的博客的《一道PHP面试题的思考》
2018-04-08
php
评论