php 如何大写连字符后的第一个字母,如亚当·史密斯-琼斯

nwnhqdif  于 2022-12-28  发布在  PHP
关注(0)|答案(9)|浏览(144)

我正在寻找一种方法来大写字符串的第一个字母/s,包括名称由连字符连接的地方,例如adam smith-jones需要成为Adam smith-jones。
ucwords()(或者ucfirst(),如果我将它们拆分为名、姓)仅适用于Adam Smith-Jones

of1yzvn4

of1yzvn41#

$string = implode('-', array_map('ucfirst', explode('-', $string)));
6ioyuze2

6ioyuze22#

你觉得下面的代码怎么样?

mb_convert_case(mb_strtolower($value, "UTF-8"), MB_CASE_TITLE, "UTF-8");

请注意,这也可以处理重音字符(对某些语言如法语有用)。

yh2wf1be

yh2wf1be3#

这样可以吗?

function to_upper($name)
    {
        $name=ucwords($name);
        $arr=explode('-', $name);
        $name=array();
        foreach($arr as $v)
        {
            $name[]=ucfirst($v);
        }
        $name=implode('-', $name);
        return $name;
    }
    echo to_upper("adam smith-jones");
aiazj4mn

aiazj4mn4#

其他方式:

<?php

$str = 'adam smith-jones';

echo preg_replace("/(-)([a-z])/e","'\\1'.strtoupper('\\2')", ucwords($str));

?>
a5g8bdjr

a5g8bdjr5#

/**
* Uppercase words including after a hyphen
*
* @param string $text lower-case text
* @return string Upper-Case text
*/
function uc_hyphenated_words($text)
{
    return str_replace("- ","-",ucwords(str_replace("-","- ",$text)));
}
nxagd54h

nxagd54h6#

<?php
     // note - this does NOT do what you want - but I think does what you said
     // perhaps you can modify it to do what you want - or we can help if you can
     // provide a bit more about the data you need to update
    $string_of_text = "We would like to welcome Adam Smith-jones to our 3rd, 'I am addicted to stackoverflow-posting' event.";
     // both Smith-Jones and Stackoverflow-Posting should result
     // may be wrong
    $words = explode(' ',$string_of_text);

    foreach($words as $index=>$word) {
       if(false !== strpos('-',$word)) {
          $parts = explode('-',$word);
          $newWords = array;
          foreach($parts as $wordIndex=>$part) {
            $newWords[] = ucwords($part);
          }
          $words[$index] = implode('-',$newWords);
       }
    }

    $words = implode(' ',$words);

?>

类似的东西-未经测试-为了确保我理解这个问题。

dzjeubhm

dzjeubhm7#

您可以使用“ucwords"一次性将所有单词大写,并将”inplode“和”explode“一起使用,如下所示:

ucwords(implode(" ", explode("_", "my_concatinated_word_string")));
yizd12fk

yizd12fk8#

function capWords($string) {
    $string = str_replace("-", " - ", $string);
    $string = ucwords(strtolower($string));
    $string = str_replace(" - ", "-", $string);

    return $string;
}
a14dhokn

a14dhokn9#

下面是一个简单的函数,可以将字符串中的所有单词转换为标题大小写:

function toTitleCase($string) {
    return preg_replace_callback('/\w+/', function ($match) {
        return ucfirst(strtolower($match[0]));
    }, $string);
}

相关问题