我是字符串操作的新手,只是尝试替换列表中的值。
我要解决的两个输入是MCAFEE
和PORT O'BRIAN
。
所以我运行ucwords(strtolower($rawTitle))
。但是,当我需要显示Mcafee
和Port O'brian
时,我现在有McAfee
和Port O'Brian
。
首先关注Port O'brian
,这是我的尝试,但显然它不起作用,因为它将字符串的第三个字母大写,而不是像我想要的第三个匹配字符:(
$oPattern = "/O\'[a-z]/"; //Pattern to match
$doesMatch = preg_match($oPattern, $output, $matches); //Do I need to the perform operation?
if ($doesMatch == 1) {
$letters = str_split($output);//break it out into an array
$cappedLetter = strtoupper($letters[2]);//capitalize the 3rd letter
$output = preg_replace("/O'$letters[2]/", $output, "O'$cappedLetter");//replace the O'x with O'X
return $output;
}
我应该在这里使用不同的功能吗?
答案 0 :(得分:2)
不,如果套管信息不在字符串中,则没有通用的方法。 (例如,考虑一下O'Hara / O'hara姓氏的两种可能的外壳。)你可以尽可能地尝试它:
$title = ucwords(strtolower($rawTitle));
$title = preg_replace_callback('/(?<=O\'|Mc)./', function($match) {
return strtoupper($match[0]);
}, $title);
但请务必事后手动检查。
答案 1 :(得分:1)
名称大写的规则可能非常复杂。这是我如何处理问题的教学示例。请参阅http://www.laprbass.com/RAY_capitalize_names.php
<?php // RAY_capitalize_names.php
error_reporting(E_ALL);
// SOME TEST NAMES
$names = array
( "o'brien"
, 'MCAFEE'
, "barrett-o'reilly"
, "smith jones"
, "burns"
, "CROWTHER"
, "George w. bush, iiI"
, "RONALD MCDONALD"
, "RONALD MCDONALD-o'brien"
, "van De Graaff GeneratoR"
)
;
// TEST EACH CASE
foreach ($names as $name)
{
echo "<br/>$name ";
echo fixname($name);
}
// FUNCTION TO HANDLE NAMES
function fixname($name)
{
// SPECIAL CASES FOR UPPER OR LOWER CASE DISPOSITION
$uc = array // UPPERCASE AFTER ANY OF THESE
( 'Mc'
, "'"
, '-'
)
;
$lc = array // ALWAYS LOWER CASE
( 'Van De '
)
;
$mc = array // ALWAYS UPPER CASE
( 'Iii'
)
;
// REMOVE UNNECESSARY BLANKS
$name = preg_replace('/\s\s+/', ' ', $name);
// START WITH LOWER CASE AND UPPER FIRST
$name = strtolower($name);
$name = ucwords($name);
// CHECK FOR KNOWN SPECIAL UPPER-CASES
foreach ($uc as $dlm)
{
// FIX THE Mcdonald EXAMPLE, ETC
$namex = explode($dlm, $name);
foreach ($namex as $k => $v)
{
$namex[$k] = ucwords($v);
}
$name = implode($dlm, $namex);
}
// CHECK FOR KNOWN CONSTANT LOWER-CASES
foreach ($lc as $dlm)
{
// FIX THE van de Graaff EXAMPLE
$name = str_replace($dlm, strtolower($dlm), $name);
}
// CHECK FOR KNOW CONSTANT UPPERCASE
foreach ($mc as $dlm)
{
// FIX THE Bush, III EXAMPLE
$name = str_replace($dlm, strtoupper($dlm), $name);
}
// RETURN THE REPAIRED STRING
return $name;
}
答案 2 :(得分:0)
将此解决方案扔出去..利用数组函数在您正在寻找的外壳中创建您的名称。它很脏,但快速有效。
1)按'
拆分 2)大写array_walk()
3)内爆。
4)对空格做同样的事情
function nameFix(&$name, $key)
{
$name = ucfirst($name);
}
function nameFixer($name)
{
$array = explode(" ", $name);
array_walk(
$array,
function (&$name, $key) {
$name = explode("'", $name);
array_walk($name, 'nameFix');
$name = implode("'", $name);
}
);
array_walk($array, nameFix);
return implode(" ", $array);
}
echo nameFixer("mister port o'hare o'brian fredrickson");
// Returns: Mister Port O'Hare O'Brian Fredrickson