繁体   English   中英

如何在php中将19a史密斯街改为19A史密斯街

[英]How can I change 19a smith STREET to 19A Smith Street in php

我想将街道地址转换为Title Case。 这不完全是Title Case,因为一串数字末尾的字母应该是大写的。 例如史密斯街19号。

我知道我可以使用“19史密斯街”改为“19史密斯街”

$str = ucwords(strtolower($str))

但是将“19a史密斯街”改为“19a史密斯街”。

如何将其转换为“19A史密斯街”?

另一种方法,更长,但可以更容易调整其他不可预见的情况,因为这是一个非常自定义的行为。

$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

这是使用正则表达式可以使用的一条路线。

$str = '19a smith STREET';
echo preg_replace_callback('~(\d+[a-z]?)(\s+.*)~', function ($matches) {
            return strtoupper($matches[1]) . ucwords(strtolower($matches[2]));
        }, $str);

输出:

史密斯街19号

正则表达式演示: https//regex101.com/r/nS9rK0/2
PHP演示: http//sandbox.onlinephpfunctions.com/code/febe99be24cf92ae3ff32fbafca63e5a81592e3c

根据Juank的回答,我实际上最终使用了。

     $str = preg_replace_callback('/([0-9])([a-z])/', function($matches){
           return $matches[1] . strtoupper($matches[2]);
      }, ucwords(strtolower($str))); 

您可以将线分成2个子串,分别格式化每个半子串,然后再将2个子串重新组合在一起。

$str = '19a smith STREET';
$split = strpos($str, ' ');
$str1 = strtoupper(substr($str, 0, $split + 1));
$str2 = ucwords(strtolower(substr($str, $split + 1)));
$str = $str1 . $str2;
echo $str;

结果:史密斯街19号

PHP演示: http//sandbox.onlinephpfunctions.com/code/9119643624c77b0c9cc584150e556a5d92c92981

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM