微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 如何在句子中用括号括起来

我使用以下代码来大写句子中的每个单词,但我无法将附加括号的单词大写.

PHP代码

  <?PHP
     $str = "[this is the {command line (interface ";
     $output  = ucwords(strtolower($str));
     echo $output;

输出

[这是{命令行(界面

但我的预期输出应该是:

[这是{命令行(接口

如何处理带括号的单词?
可能有多个括号.

例如:

[{this is the({command line({(interface

我想在PHP中找到一个通用的解决方案/函数.

解决方法:

$output = ucwords($str, ' [{(');
echo $output;
// output ->
// [This Is The {Command Line (Interface

更新:一般解决方案.这里的“括号” – 是任何非字母字符. “括号”后面的任何字母都会转换为大写.

$string = "test is the {COMMAND line -STRET (interface 5more 9words #here";
$strlowercase = strtolower($string);

$result = preg_replace_callback('~(^|[^a-zA-Z])([a-z])~', function($matches)
{
    return $matches[1] . ucfirst($matches[2]);
}, $strlowercase);


var_dump($result);
// string(62) "Test Is The {Command Line -Stret (Interface 5More 9Words #Here"

直播demo

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐