[PHP]strtoupper関数を完全解説!文字列を大文字に変換する方法

PHP

こんにちは!今回は、PHPの標準関数であるstrtoupper()について詳しく解説していきます。文字列をすべて大文字に変換する、シンプルだけど非常によく使われる関数です!

strtoupper関数とは?

strtoupper()関数は、文字列内のすべての英字を大文字に変換する関数です。

“string to upper”の略で、データの正規化、表示の統一、比較処理など、様々な用途で使用されます!

基本的な構文

strtoupper(string $string): string
  • $string: 大文字に変換する文字列
  • 戻り値: 大文字に変換された文字列

基本的な使用例

シンプルな変換

// 小文字を大文字に
$text = "hello world";
echo strtoupper($text) . "\n";
// 出力: HELLO WORLD

// 混在した文字列
$text = "Hello World";
echo strtoupper($text) . "\n";
// 出力: HELLO WORLD

// すでに大文字の場合
$text = "HELLO";
echo strtoupper($text) . "\n";
// 出力: HELLO(変化なし)

数字と記号

// 数字と記号は変化しない
$text = "abc123!@#";
echo strtoupper($text) . "\n";
// 出力: ABC123!@#

$text = "test-case_2024";
echo strtoupper($text) . "\n";
// 出力: TEST-CASE_2024

マルチバイト文字の扱い

// ASCII文字のみ処理される
$text = "hello こんにちは world";
echo strtoupper($text) . "\n";
// 出力: HELLO こんにちは WORLD

// 日本語は変化しない
$text = "テスト test テスト";
echo strtoupper($text) . "\n";
// 出力: テスト TEST テスト

// マルチバイト対応が必要な場合
$text = "hello";
echo mb_strtoupper($text, 'UTF-8') . "\n";
// 出力: HELLO

実践的な使用例

例1: 定数名とキーの生成

class ConstantGenerator {
    /**
     * 定数名を生成
     */
    public static function generateConstantName($text) {
        // 大文字に変換
        $constant = strtoupper($text);
        
        // スペースをアンダースコアに
        $constant = str_replace(' ', '_', $constant);
        
        // 英数字とアンダースコアのみに
        $constant = preg_replace('/[^A-Z0-9_]/', '', $constant);
        
        return $constant;
    }
    
    /**
     * 環境変数名を生成
     */
    public static function generateEnvName($text) {
        $envName = self::generateConstantName($text);
        
        // プレフィックスを追加
        return 'APP_' . $envName;
    }
    
    /**
     * 配列キーを正規化
     */
    public static function normalizeArrayKey($key) {
        return strtoupper(trim($key));
    }
    
    /**
     * HTTPヘッダー名を正規化
     */
    public static function normalizeHeaderName($header) {
        // 大文字に変換
        $header = strtoupper($header);
        
        // ハイフンをアンダースコアに
        $header = str_replace('-', '_', $header);
        
        return $header;
    }
}

// 使用例
$names = [
    'database host',
    'max-connections',
    'cache.enabled',
    'debug mode'
];

echo "=== 定数名生成 ===\n";
foreach ($names as $name) {
    echo "{$name} → " . ConstantGenerator::generateConstantName($name) . "\n";
}
/*
database host → DATABASE_HOST
max-connections → MAXCONNECTIONS
cache.enabled → CACHEENABLED
debug mode → DEBUG_MODE
*/

echo "\n=== 環境変数名 ===\n";
foreach ($names as $name) {
    echo "{$name} → " . ConstantGenerator::generateEnvName($name) . "\n";
}

echo "\n=== HTTPヘッダー正規化 ===\n";
$headers = ['content-type', 'authorization', 'x-api-key'];
foreach ($headers as $header) {
    echo "{$header} → " . ConstantGenerator::normalizeHeaderName($header) . "\n";
}

例2: データベースとSQL

class SqlFormatter {
    /**
     * SQLキーワードを大文字に
     */
    public static function formatKeywords($sql) {
        $keywords = [
            'select', 'from', 'where', 'and', 'or', 'order', 'by',
            'group', 'having', 'limit', 'offset', 'join', 'left',
            'right', 'inner', 'outer', 'on', 'as', 'insert', 'into',
            'values', 'update', 'set', 'delete', 'create', 'table',
            'drop', 'alter', 'add', 'column'
        ];
        
        foreach ($keywords as $keyword) {
            $pattern = '/\b' . $keyword . '\b/i';
            $sql = preg_replace($pattern, strtoupper($keyword), $sql);
        }
        
        return $sql;
    }
    
    /**
     * テーブル名を大文字に
     */
    public static function normalizeTableName($tableName) {
        return strtoupper($tableName);
    }
    
    /**
     * カラム名を大文字に
     */
    public static function normalizeColumnName($columnName) {
        return strtoupper($columnName);
    }
    
    /**
     * クエリをフォーマット
     */
    public static function formatQuery($sql) {
        // キーワードを大文字に
        $sql = self::formatKeywords($sql);
        
        // 改行とインデントを整形
        $sql = str_replace(' FROM ', "\nFROM ", $sql);
        $sql = str_replace(' WHERE ', "\nWHERE ", $sql);
        $sql = str_replace(' ORDER BY ', "\nORDER BY ", $sql);
        
        return $sql;
    }
}

// 使用例
$sql = "select id, name, email from users where status = 'active' order by created_at desc";

echo "=== SQL整形 ===\n";
echo "元のSQL:\n{$sql}\n\n";
echo "整形後:\n" . SqlFormatter::formatQuery($sql) . "\n";

echo "\n=== テーブル名正規化 ===\n";
$tables = ['users', 'products', 'orders'];
foreach ($tables as $table) {
    echo "{$table} → " . SqlFormatter::normalizeTableName($table) . "\n";
}

例3: ファイルとディレクトリ処理

class FileSystemNormalizer {
    /**
     * ドライブレターを大文字に
     */
    public static function normalizeDriveLetter($path) {
        // Windowsパスのドライブレターを大文字に
        if (preg_match('/^([a-z]):/i', $path, $matches)) {
            $driveLetter = strtoupper($matches[1]);
            $path = $driveLetter . substr($path, 1);
        }
        
        return $path;
    }
    
    /**
     * 拡張子を大文字に
     */
    public static function uppercaseExtension($filename) {
        $info = pathinfo($filename);
        $basename = $info['filename'];
        $extension = isset($info['extension']) ? $info['extension'] : '';
        
        if (!empty($extension)) {
            return $basename . '.' . strtoupper($extension);
        }
        
        return $basename;
    }
    
    /**
     * ファイル名を大文字に
     */
    public static function uppercaseFilename($path) {
        $dirname = dirname($path);
        $basename = basename($path);
        
        $basename = strtoupper($basename);
        
        if ($dirname === '.') {
            return $basename;
        }
        
        return $dirname . DIRECTORY_SEPARATOR . $basename;
    }
    
    /**
     * 拡張子で分類(大文字小文字無視)
     */
    public static function groupByExtension($files) {
        $grouped = [];
        
        foreach ($files as $file) {
            $ext = strtoupper(pathinfo($file, PATHINFO_EXTENSION));
            
            if (!isset($grouped[$ext])) {
                $grouped[$ext] = [];
            }
            
            $grouped[$ext][] = $file;
        }
        
        return $grouped;
    }
}

// 使用例
$paths = [
    'c:/users/documents/file.txt',
    'd:/projects/test.php',
    '/var/www/html/index.html'
];

echo "=== ドライブレター正規化 ===\n";
foreach ($paths as $path) {
    echo "{$path} → " . FileSystemNormalizer::normalizeDriveLetter($path) . "\n";
}

$files = ['document.pdf', 'image.jpg', 'report.docx'];
echo "\n=== 拡張子を大文字に ===\n";
foreach ($files as $file) {
    echo "{$file} → " . FileSystemNormalizer::uppercaseExtension($file) . "\n";
}

echo "\n=== 拡張子でグループ化 ===\n";
$allFiles = ['test.PDF', 'image.jpg', 'doc.PDF', 'photo.JPG'];
$grouped = FileSystemNormalizer::groupByExtension($allFiles);
print_r($grouped);

例4: プロトコルとスキーム

class ProtocolHandler {
    /**
     * プロトコルを大文字に
     */
    public static function normalizeProtocol($url) {
        if (preg_match('/^([a-z]+):\/\//i', $url, $matches)) {
            $protocol = strtoupper($matches[1]);
            return $protocol . substr($url, strlen($matches[1]));
        }
        
        return $url;
    }
    
    /**
     * スキームを取得(大文字)
     */
    public static function getScheme($url) {
        if (preg_match('/^([a-z]+):/i', $url, $matches)) {
            return strtoupper($matches[1]);
        }
        
        return null;
    }
    
    /**
     * プロトコルが一致するかチェック
     */
    public static function hasProtocol($url, $protocol) {
        $scheme = self::getScheme($url);
        return $scheme === strtoupper($protocol);
    }
    
    /**
     * セキュアプロトコルかチェック
     */
    public static function isSecure($url) {
        $scheme = self::getScheme($url);
        return in_array($scheme, ['HTTPS', 'FTPS', 'SSH']);
    }
}

// 使用例
$urls = [
    'http://example.com',
    'HTTPS://secure.example.com',
    'ftp://files.example.com',
    'ssh://server.example.com'
];

echo "=== プロトコル正規化 ===\n";
foreach ($urls as $url) {
    echo "{$url} → " . ProtocolHandler::normalizeProtocol($url) . "\n";
}

echo "\n=== スキーム取得 ===\n";
foreach ($urls as $url) {
    echo "{$url}: " . ProtocolHandler::getScheme($url) . "\n";
}

echo "\n=== セキュアチェック ===\n";
foreach ($urls as $url) {
    $secure = ProtocolHandler::isSecure($url) ? 'セキュア' : '非セキュア';
    echo "{$url}: {$secure}\n";
}

例5: コード生成

class CodeGenerator {
    /**
     * クラス定数を生成
     */
    public static function generateConstants($data) {
        $constants = [];
        
        foreach ($data as $key => $value) {
            $constantName = strtoupper($key);
            
            if (is_string($value)) {
                $value = "'{$value}'";
            } elseif (is_bool($value)) {
                $value = $value ? 'true' : 'false';
            } elseif (is_null($value)) {
                $value = 'null';
            }
            
            $constants[] = "const {$constantName} = {$value};";
        }
        
        return implode("\n    ", $constants);
    }
    
    /**
     * 列挙型を生成
     */
    public static function generateEnum($name, $values) {
        $name = strtoupper($name);
        $enumValues = [];
        
        foreach ($values as $value) {
            $enumValues[] = strtoupper($value);
        }
        
        return "enum {$name} {\n    " . 
               implode(",\n    ", $enumValues) . 
               "\n}";
    }
    
    /**
     * 定義を生成
     */
    public static function generateDefine($name, $value) {
        $name = strtoupper($name);
        
        if (is_string($value)) {
            $value = "'{$value}'";
        }
        
        return "define('{$name}', {$value});";
    }
}

// 使用例
$config = [
    'db_host' => 'localhost',
    'db_port' => 3306,
    'debug_mode' => true,
    'api_key' => null
];

echo "=== 定数生成 ===\n";
echo "class Config {\n    ";
echo CodeGenerator::generateConstants($config);
echo "\n}\n";

echo "\n=== 列挙型生成 ===\n";
$statuses = ['pending', 'approved', 'rejected'];
echo CodeGenerator::generateEnum('Status', $statuses) . "\n";

echo "\n=== define生成 ===\n";
echo CodeGenerator::generateDefine('app_name', 'MyApp') . "\n";
echo CodeGenerator::generateDefine('max_users', 100) . "\n";

例6: HTTPヘッダーとメソッド

class HttpHandler {
    /**
     * HTTPメソッドを正規化
     */
    public static function normalizeMethod($method) {
        return strtoupper($method);
    }
    
    /**
     * HTTPヘッダーを整形
     */
    public static function formatHeaders($headers) {
        $formatted = [];
        
        foreach ($headers as $name => $value) {
            // ヘッダー名を大文字に
            $name = strtoupper($name);
            $formatted[$name] = $value;
        }
        
        return $formatted;
    }
    
    /**
     * ステータスコードの説明を取得
     */
    public static function getStatusText($code) {
        $statuses = [
            200 => 'OK',
            201 => 'CREATED',
            204 => 'NO CONTENT',
            400 => 'BAD REQUEST',
            401 => 'UNAUTHORIZED',
            403 => 'FORBIDDEN',
            404 => 'NOT FOUND',
            500 => 'INTERNAL SERVER ERROR'
        ];
        
        return $statuses[$code] ?? 'UNKNOWN';
    }
    
    /**
     * メソッドが安全かチェック
     */
    public static function isSafeMethod($method) {
        $method = strtoupper($method);
        return in_array($method, ['GET', 'HEAD', 'OPTIONS']);
    }
    
    /**
     * メソッドがべき等かチェック
     */
    public static function isIdempotentMethod($method) {
        $method = strtoupper($method);
        return in_array($method, ['GET', 'HEAD', 'PUT', 'DELETE', 'OPTIONS']);
    }
}

// 使用例
$methods = ['get', 'POST', 'put', 'Delete', 'PATCH'];

echo "=== HTTPメソッド正規化 ===\n";
foreach ($methods as $method) {
    echo "{$method} → " . HttpHandler::normalizeMethod($method) . "\n";
}

$headers = [
    'content-type' => 'application/json',
    'authorization' => 'Bearer token123',
    'x-api-key' => 'abc123'
];

echo "\n=== ヘッダー整形 ===\n";
$formatted = HttpHandler::formatHeaders($headers);
print_r($formatted);

echo "\n=== ステータステキスト ===\n";
$codes = [200, 404, 500];
foreach ($codes as $code) {
    echo "{$code}: " . HttpHandler::getStatusText($code) . "\n";
}

echo "\n=== メソッド分類 ===\n";
foreach ($methods as $method) {
    $safe = HttpHandler::isSafeMethod($method) ? 'Safe' : 'Not Safe';
    $idempotent = HttpHandler::isIdempotentMethod($method) ? 'Idempotent' : 'Not Idempotent';
    echo "{$method}: {$safe}, {$idempotent}\n";
}

例7: 略語と頭字語

class AcronymHandler {
    /**
     * 略語を大文字に
     */
    public static function formatAcronym($text) {
        return strtoupper($text);
    }
    
    /**
     * テキスト内の既知の略語を大文字に
     */
    public static function capitalizeAcronyms($text, $acronyms) {
        foreach ($acronyms as $acronym) {
            $pattern = '/\b' . preg_quote($acronym, '/') . '\b/i';
            $text = preg_replace($pattern, strtoupper($acronym), $text);
        }
        
        return $text;
    }
    
    /**
     * 頭字語を生成
     */
    public static function generateAcronym($phrase) {
        $words = explode(' ', $phrase);
        $acronym = '';
        
        foreach ($words as $word) {
            if (!empty($word)) {
                $acronym .= strtoupper($word[0]);
            }
        }
        
        return $acronym;
    }
    
    /**
     * 技術用語を正規化
     */
    public static function normalizeTechTerms($text) {
        $terms = [
            'html' => 'HTML',
            'css' => 'CSS',
            'php' => 'PHP',
            'sql' => 'SQL',
            'api' => 'API',
            'json' => 'JSON',
            'xml' => 'XML',
            'http' => 'HTTP',
            'https' => 'HTTPS'
        ];
        
        foreach ($terms as $lower => $upper) {
            $pattern = '/\b' . $lower . '\b/i';
            $text = preg_replace($pattern, $upper, $text);
        }
        
        return $text;
    }
}

// 使用例
echo "=== 略語整形 ===\n";
$acronyms = ['usa', 'nasa', 'fbi', 'cia'];
foreach ($acronyms as $acronym) {
    echo "{$acronym} → " . AcronymHandler::formatAcronym($acronym) . "\n";
}

echo "\n=== テキスト内の略語 ===\n";
$text = "The usa and nasa work together. The fbi and cia coordinate.";
$knownAcronyms = ['usa', 'nasa', 'fbi', 'cia'];
echo AcronymHandler::capitalizeAcronyms($text, $knownAcronyms) . "\n";

echo "\n=== 頭字語生成 ===\n";
$phrases = [
    'Hypertext Markup Language',
    'Application Programming Interface',
    'Structured Query Language'
];
foreach ($phrases as $phrase) {
    echo "{$phrase} → " . AcronymHandler::generateAcronym($phrase) . "\n";
}

echo "\n=== 技術用語正規化 ===\n";
$techText = "I use php to create an api that returns json data via https.";
echo AcronymHandler::normalizeTechTerms($techText) . "\n";

例8: 比較とマッチング

class CaseInsensitiveMatcher {
    /**
     * 大文字小文字を区別しない比較
     */
    public static function equals($str1, $str2) {
        return strtoupper($str1) === strtoupper($str2);
    }
    
    /**
     * 配列内に存在するかチェック
     */
    public static function inArray($needle, $haystack) {
        $needle = strtoupper($needle);
        
        foreach ($haystack as $item) {
            if (strtoupper($item) === $needle) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * パターンマッチング
     */
    public static function matchesPattern($text, $pattern) {
        return strtoupper($text) === strtoupper($pattern);
    }
    
    /**
     * 先頭が一致するかチェック
     */
    public static function startsWith($haystack, $needle) {
        $needleUpper = strtoupper($needle);
        $haystackStart = strtoupper(substr($haystack, 0, strlen($needle)));
        
        return $haystackStart === $needleUpper;
    }
}

// 使用例
echo "=== 大文字小文字無視比較 ===\n";
var_dump(CaseInsensitiveMatcher::equals('Hello', 'HELLO'));  // true
var_dump(CaseInsensitiveMatcher::equals('Hello', 'World'));  // false

$array = ['Apple', 'Banana', 'CHERRY'];
echo "\n=== 配列内検索 ===\n";
var_dump(CaseInsensitiveMatcher::inArray('apple', $array));   // true
var_dump(CaseInsensitiveMatcher::inArray('BANANA', $array));  // true
var_dump(CaseInsensitiveMatcher::inArray('grape', $array));   // false

echo "\n=== 前方一致 ===\n";
var_dump(CaseInsensitiveMatcher::startsWith('HelloWorld', 'hello'));  // true
var_dump(CaseInsensitiveMatcher::startsWith('HelloWorld', 'HELLO'));  // true

strtolower()との関係

$text = "Hello World";

// strtoupper(): 大文字に変換
echo strtoupper($text) . "\n";  // HELLO WORLD

// strtolower(): 小文字に変換
echo strtolower($text) . "\n";  // hello world

// 往復変換
$upper = strtoupper($text);
$lower = strtolower($upper);
echo $lower . "\n";  // hello world

パフォーマンスの考慮

// 大量のデータで大文字変換
$text = str_repeat("abcdefghijklmnopqrstuvwxyz", 10000);

// strtoupper()
$start = microtime(true);
for ($i = 0; $i < 1000; $i++) {
    strtoupper($text);
}
$time1 = microtime(true) - $start;

// 手動変換
$start = microtime(true);
for ($i = 0; $i < 1000; $i++) {
    $result = '';
    for ($j = 0; $j < strlen($text); $j++) {
        $char = $text[$j];
        if ($char >= 'a' && $char <= 'z') {
            $result .= chr(ord($char) - 32);
        } else {
            $result .= $char;
        }
    }
}
$time2 = microtime(true) - $start;

echo "strtoupper(): {$time1}秒\n";
echo "手動変換: {$time2}秒\n";

// strtoupper()は高度に最適化されており非常に高速

まとめ

strtoupper()関数の特徴をまとめると:

できること:

  • 文字列を大文字に変換
  • 定数名・環境変数名の生成
  • プロトコル・メソッドの正規化

推奨される使用場面:

  • 定数名の生成
  • SQL文の整形
  • HTTPメソッド・ヘッダーの正規化
  • プロトコルスキームの処理
  • 略語・頭字語の整形
  • コード生成

注意点:

  • ASCII文字のみ処理(a-z → A-Z)
  • マルチバイト文字にはmb_strtoupper()を使用
  • 元の文字列は変更されない

関連関数:

  • strtolower(): 小文字に変換
  • ucfirst(): 最初の文字を大文字に
  • ucwords(): 各単語の最初を大文字に
  • mb_strtoupper(): マルチバイト対応版
  • lcfirst(): 最初の文字を小文字に

大文字小文字の統一:

// 定数名として使用
define(strtoupper('app_name'), 'MyApp');

// HTTPメソッドの正規化
$method = strtoupper($_SERVER['REQUEST_METHOD']);

// SQLキーワードの整形
$sql = strtoupper('select') . ' * FROM users';

パフォーマンス:

  • 非常に高速(C言語レベルで最適化)
  • 大量のデータでも効率的

strtoupper()は、データの正規化や定数名の生成など、様々な場面で活躍する関数です。特にコード生成やプロトコル処理では頻繁に使用されるので、適切に使いこなしましょう!

タイトルとURLをコピーしました