将 PHP 中字符串中的每个(通配符)实例大写

Capitalising every instance of a (wildcard) in a string in PHP

我正在尝试编写一个函数,将字符串中人名的每个实例都大写,它需要是动态的,以便名称可以更改。例如

"Hello Mr harrison and Mr jones" 会变成 "Hello Mr Harrison and Mr Jones".

是否有一种有效的方法来执行此操作而不只是计算字母数?

编辑:为了澄清,我将从数据库中获取 4-5 个句子的字符串,这是公司工程师留下的简短描述。下面的函数格式化文本,所以不管他们是用全大写还是不大写都没有关系。但是,它需要查找并更正 Mr.(然后是人名)的实例。

示例 - 如果工程师留下的评论为 "I HAVE FIXED MR JONES FRIDGE. MR JONES WAS HAPPY WITH THE SERVICE" - 这将被转换为

"I have fixed Mr jones fridge. Mr jones was happy with the service"

编辑:到目前为止,这是我设置文本格式的功能。

function formatTextCase($string) 
// Format a string to correct upper and lower case E.g. "HELLO. goodbye." "to Hello. Goodbye."
{
// Trime whitespace
$string = trim($string);

// First format to all lower, and capitalise first letter
$string = ucfirst(strtolower($string));     

// Capitalise any letter after full stop.
$string = preg_replace_callback('/[.!?:;].*?\w/', create_function('$matches', 'return strtoupper($matches[0]);'), $string);

// Test - please remove
//$string .= " Hello i am testing.";

// Replace any lower case I
$string = str_replace(" i ", " I ", $string);

// Now locate and capitalise any name after "Mr" eg. Mr jones to Mr Jones
What do I do here?

return $string;
}

谢谢!

@iainn 使用正则表达式有一个更优化的答案。但我想出的另一种解决方案是,如下

$string = "Hello my name is Mr jackson and my friend is Mrs jones";

$splitString= explode(' ', $string);

foreach($splitString as $k=>$v){

  if(stristr($v, "Mr") || stristr($v, "Mrs")){
      $splitString[$k + 1] = ucfirst($splitString[$k + 1]);
  }

}

$string = implode(" ", $splitString);

echo $string;

这是我为您精心制作的热门作品:

代码:(PHP Demo) (Pattern Demo)

function uppers($m){
    $edge_cases=['De ','Di ','Du ','De La ','Van '];
    $correction=['de ','di ','du ','de la ','van '];  // reverse some fringe case names
    return str_replace($edge_cases,$correction,ucwords($m[0],"-' "));  // notice 2nd param of ucwords()
}

$sentences="i have fixed mr jones fridge.  mrs jones was happy with the service.  miss johnson-taylor told ms o'neil that everything was fabulous.  mr van larsen was less than impressed but that was a missunderstanding.  another person liked us on facebook!";
$sentences=preg_split('/[.!?]\K\s+/',$sentences); // generate array of sentences
$sentences=preg_replace_callback('/\bm(?:iss|r?s?)\b (?:de |di |du |de la |van )?[a-z]+[-\']?[a-z]*/','uppers',$sentences);  // match full names
$sentences=implode('  ',array_map('ucfirst',$sentences));  // capitalize start of sentences and rejoin sentences into a string
echo $sentences;

输出:

I have fixed Mr Jones fridge.  Mrs Jones was happy with the service.  Miss Johnson-Taylor told Ms O'Neil that everything was fabulous.  Mr van Larsen was less than impressed but that was a missunderstanding.  Another person liked us on facebook!