我想把街道地址转换成类似地契的东西。这并不完全是标题大小写,因为数字串末尾的字母应该是大写字母。史密斯街19 A。
我知道我可以把"19史密斯街“改为"19史密斯街”
$str = ucwords(strtolower($str))但这会把"19a史密斯街“改成"19a史密斯街”。
我怎样才能把它改成"19A史密斯街“呢?
发布于 2015-07-07 03:04:01
另一种方法,由于这是一种非常自定义的行为,更长,但可能更容易对其他未见的场景进行调整。
$string = "19a smith STREET";
// normalize everything to lower case
$string = strtolower($string);
// all words with upper case
$string = ucwords($string);
// replace any letter right after a number with its uppercase version
$string = preg_replace_callback('/([0-9])([a-z])/', function($matches){
return $matches[1] . strtoupper($matches[2]);
}, $string);
echo $string;
// echoes 19A Smith Street
// 19-45n carlsBERG aVenue -> 19-45N Carlsberg Avenue发布于 2015-07-07 02:55:54
这是一条你可以使用正则表达式的路线。
$str = '19a smith STREET';
echo preg_replace_callback('~(\d+[a-z]?)(\s+.*)~', function ($matches) {
return strtoupper($matches[1]) . ucwords(strtolower($matches[2]));
}, $str);输出:
史密斯街19A号
Regex演示:https://regex101.com/r/nS9rK0/2
PHP演示:http://sandbox.onlinephpfunctions.com/code/febe99be24cf92ae3ff32fbafca63e5a81592e3c
发布于 2015-07-07 11:50:13
根据胡安克的回答,我最终使用了。
$str = preg_replace_callback('/([0-9])([a-z])/', function($matches){
return $matches[1] . strtoupper($matches[2]);
}, ucwords(strtolower($str))); https://stackoverflow.com/questions/31258876
复制相似问题