开发者

Detect capitalization of a string and apply it to another string in PHP

开发者 https://www.devze.com 2023-02-16 23:49 出处:网络
As the title suggests i\'m trying to detect the capitalization of a string and apply that same formatting to a new string.

As the title suggests i'm trying to detect the capitalization of a string and apply that same formatting to a new string.

Example:

Yellow cheese >>> detect that it's only the f开发者_开发问答irst character capitalized >>> change blue cheese to Blue cheese.

Is this possible?


Kind of depends on how smart you need the algorithm to be. A simple one could be simply something like:

<?php
$v1 = "Yellow cheese";
$v2 = "blue cheese";
$out = "";
for($i = 0; $i < max(strlen($v1), strlen($v2)); $i++) {
  if($v1[i] === strtoupper($v1[i])) {
    $out .= strtoupper($v2[i]);
  } else {
    $out .= strtolower($v2[i]);
  }
}

This will do it very blindly, so

  YelLoW ChEEse
> BluE CHEsSE


You could try :

$ref = 'Yellow cheese';
$str = 'blue cheese';
$ref_words = explode(' ', $ref);
$str_words = explode(' ', $str);
for($i=0; $i<count($ref_words); $i++) {
    if (preg_match('/^[A-Z]/', $ref_words[$i])) {
        $str_words[$i] = ucfirst($str_words[$i]);
    }
}
$res = implode(' ', $str_words);
echo $res,"\n";

output:

Blue cheese
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号