首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我如何在php中将19a史密斯街改为19A史密斯街

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

Stack Overflow用户
提问于 2015-07-07 02:42:20
回答 4查看 85关注 0票数 8

我想把街道地址转换成类似地契的东西。这并不完全是标题大小写,因为数字串末尾的字母应该是大写字母。史密斯街19 A。

我知道我可以把"19史密斯街“改为"19史密斯街”

代码语言:javascript
复制
$str = ucwords(strtolower($str))

但这会把"19a史密斯街“改成"19a史密斯街”。

我怎样才能把它改成"19A史密斯街“呢?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2015-07-07 03:04:01

另一种方法,由于这是一种非常自定义的行为,更长,但可能更容易对其他未见的场景进行调整。

代码语言:javascript
复制
$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
票数 4
EN

Stack Overflow用户

发布于 2015-07-07 02:55:54

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

代码语言:javascript
复制
$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

票数 1
EN

Stack Overflow用户

发布于 2015-07-07 11:50:13

根据胡安克的回答,我最终使用了。

代码语言:javascript
复制
     $str = preg_replace_callback('/([0-9])([a-z])/', function($matches){
           return $matches[1] . strtoupper($matches[2]);
      }, ucwords(strtolower($str))); 
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31258876

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档