LoginSignup
0
0

More than 5 years have passed since last update.

PHP 先頭の単語を大文字にする

Posted at

今回挑戦するプログラミング問題

codewars 5級
「The Hashtag Generator」

実現したいこと

  • #をつけて返す
  • 各文字列の最初を大文字にする
  • 返す文字列が140文字以上の場合はfalseとする
  • 空文字列が与えられば場合はfalseとする
" Hello there thanks for trying my Kata"  =>  "#HelloThereThanksForTryingMyKata"
"    Hello     World   "                  =>  "#HelloWorld"
""                                        =>  false

コーディング

function generateHashtag($str) {
  $result = '#'.$str = str_replace(' ', '', ucwords($str));
  if(empty($str) || strlen($result) > 140) return false;
  return $result;
}
  • ucwords()で各単語の最初の文字を大文字にする
  • str_replaceでスペースを取り除き、先頭に#をつける
  • 条件を確認して結果を返す
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0