dongme8388 2012-04-13 14:45
浏览 35
已采纳

PHP:规范化一个字符串

I want to normalize (so canonicalize) a string into the normal form for names:

  1. First letter of the name is uppercase

The difficulty by this is now to follow this rule with second and third name.

My method:

    public function namilize($string)
{
    $strings = explode(' ', $string);
    foreach ($strings as $string) {
        $string = ucfirst(strtolower($string));
    }
    $string = implode(' ', $strings);

    return $string;
}

Somehow the

$string = ucfirst(strtolower($string));

fails.

What do I have to correct? Is there a better way?

Regards

EDIT:

Hi,

thank you all for all the comments and answers. I found another "modern" method:

public function namilize($string)
{
    $string = mb_convert_case($string, MB_CASE_TITLE, mb_detect_encoding($string));
}

When I now would additionally add some regex for Mc and O's than it would be complete :)

  • 写回答

3条回答 默认 最新

  • dongzu0742 2012-04-13 15:04
    关注
    public function namilize($name) {
        $name = strtolower($name);
        $normalized = array();
    
        foreach (preg_split('/([^a-z])/', $name, NULL, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY) as $word) {
            if (preg_match('/^(mc)(.*)$/', $word, $matches)) {
                $word = $matches[1] . ucfirst($matches[2]);
            }
    
            $normalized[] = ucfirst($word);
        }
    
        return implode('', $normalized);
    }
    

    Note that this will work for names like John O'Brian, James McManus, etc. For other names with prefixes like McManus, simply add the prefix to the preg_match(). Obviously, this runs the possibility of false positives, but no method is going to be 100% foolproof.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探