【问题标题】:How to capitalize words with brackets in sentence [duplicate]如何在句子中将带括号的单词大写[重复]
【发布时间】:2017-06-05 17:35:48
【问题描述】:

我正在使用以下代码将句子中的每个单词大写,但我无法将带有括号的单词大写。

PHP 代码:

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

输出:

[this Is The {command Line (interface

但我的预期输出应该是:

[This Is The {Command Line (Interface

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

例如:

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

我想在 PHP 中找到一个通用的解决方案/功能。

【问题讨论】:

标签: php


【解决方案1】:
$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

【讨论】:

  • 可能不想要strtolowerCLIPHP 会发生什么?
  • 另一个我想包含带有起始词的数字怎么做。示例 3s [这是命令行{本例中的接口 's' 应该是大写。
  • 我已经添加了 $output = ucwords($str, ' [{(123456789'); 但我有更多超过 15 的括号.. 有适当的解决方案来处理所有括号而无需定义。因为用户可以添加任何未在我的代码中定义的括号。
  • @Joe Black 但是这个 "-STRET" 字母没有转换成 "-Stret" 。请看这个。首先我需要所有的小写字母,然后是大写的第一个字母。
  • @RaheelAslam 添加了strtolower()。请检查一下
【解决方案2】:

这是另一种解决方案,如果要处理更多字符,可以在 for-each 循环数组中添加更多分隔符。

function ucname($string) {
    $string =ucwords(strtolower($string));

    foreach (array('-', '\'') as $delimiter) {
      if (strpos($string, $delimiter)!==false) {
        $string =implode($delimiter, array_map('ucfirst', explode($delimiter, $string)));
      }
    }
    return $string;
}
?>
<?php
//TEST

$names =array(
  'JEAN-LUC PICARD',
  'MILES O\'BRIEN',
  'WILLIAM RIKER',
  'geordi la forge',
  'bEvErly CRuSHeR'
);
foreach ($names as $name) { print ucname("{$name}\n<br />"); }

//PRINTS:
/*
Jean-Luc Picard
Miles O'Brien
William Riker
Geordi La Forge
Beverly Crusher
*/

【讨论】:

    猜你喜欢
    • 2018-04-24
    • 2020-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-19
    • 1970-01-01
    • 1970-01-01
    • 2011-01-26
    相关资源
    最近更新 更多