如何使ucwords只适用于单引号而不适用于撇号


How to make ucwords work for single quotes only and not apostrophes?

我想把这个文本变成:

她说是时候"找到解决方案"了。

转换为文本:

她说是时候"找到解决方案"了。

我目前正在使用ucwords和这个与ucwords相关的函数在单引号后面加大写字母:(我在php.net的评论部分找到了。)

function ucwordsMore ($str) {
    $str = str_replace("' ","'",ucwords(str_replace("'","' ",$str)));
    return $str;
}

然而,此功能的结果是:

她说是时候"找到解决方案"了。

如何最好地保留撇号后的字母小和单引号后的

它通常使用一些模式匹配:

$str = preg_replace("/'w['w']*/e", "ucwords('''0')", $str);

'w适用于ASCII字母和数字。对于国际文本,请使用'pL/u修饰符。

抱歉,单引号和撇号没有区别。如果有意义的话,你必须用一些东西来区分两者。你可以使用的一种启发式方法是,如果撇号后面只有一个或两个连续的字符,你可以假设它是一个缩写,而不是一个单引号字符串。

编辑:这是一个愚蠢的启发式,我不推荐,但我还是做了。

function ucwordsMore ($str) {
    $str = str_replace("' ","'",ucwords(str_replace("'","' ",$str)));
    return $str;
}
$string  = "She's Saying It's Time To 'Find A Solution'.";
$string = ucwordsMore($string);
//string now equals = She'S Saying It'S Time To 'Find A Solution'.
for($i = 0; $i < strlen($string); $i++){
    if($string[$i] == "'"){
      if($i +2 < strlen($string) && $string[$i] == "'"&& $string[$i+1] != " "&& $string[$i+2] == " "){
          $string[$i+1] = strtolower($string[$i+1]); //replace
    }
      if($i +3 < strlen($string) && $string[$i] == "'"&& $string[$i+1] != " "&& $string[$i+2] != " "&& $string[$i+3] == " "){
          $string[$i+1] = strtolower($string[$i+1]); //replace
          $string[$i+2] = strtolower($string[$i+2]); //replace
    }
}
}
echo $string;
//$string - "She's Saying It's Time To 'Find A Solution'."
$str = ucwords($str);
$str = preg_replace_callback("/(^|''s+)'[a-z]/", create_function(
    '$matches',
    'return strtoupper($matches[0]);'
), $str);
相关文章: