【问题标题】:preg_match to check for upper case of first letter of each word in a stringpreg_match 检查字符串中每个单词的首字母是否大写
【发布时间】:2010-11-10 22:28:11
【问题描述】:

我遇到了这个 php ucfirst() 来使字符串中每个单词的第一个字符大写。

$foo = 'hello world!';
$foo = ucfirst($foo); 

但是如何使用正则表达式和 preg_match() 进行检查,然后显示错误信息?

if (preg_match('/\b\p{Ll}/', $mem_titlename))
{
   $error = true;
   echo '<error elementid="mem_titlename" message="TITLE - please use uppercase for each word."/>';
}

不确定上面示例中该表达式的含义,但我从与 ucfirst() 执行相同工作的某个地方得到它...

【问题讨论】:

    标签: php regex preg-match


    【解决方案1】:

    为什么要使用正则表达式?如果ucwords() 做你想做的,这似乎是不必要的。如果是这样,只需以下内容:

    if (ucwords($mem_titlename) == $mem_titlename) {
       $error = true;
       echo '<error elementid="mem_titlename" message="TITLE - please use uppercase for each word."/>';
    }
    

    另请注意,ucwords() 执行您所描述的操作,而不是 ucfirst()http://www.php.net/manual/en/function.ucwords.php

    【讨论】:

    • +1。对于这样的简单任务,无需使用正则表达式。
    • @You,同意。虽然是一个很棒的工具,但不幸的是,我发现它们在错误实例中的使用频率比在正确中的使用频率要高。
    猜你喜欢
    • 2011-01-20
    • 2019-08-14
    • 2014-06-19
    • 2014-05-19
    • 2021-09-07
    • 2010-12-05
    相关资源
    最近更新 更多