はじめに

PHPソースコードからクラス名やメソッド情報を抽出したい場合、正規表現で解析できます。ドキュメント自動生成などに活用できます。

クラス名と名前空間の抽出

$content = file_get_contents($filePath);

// 名前空間
preg_match('/namespace\s+([\w\\\\]+)\s*;/', $content, $nsMatch);
$namespace = $nsMatch[1] ?? '';

// クラス名
preg_match('/^\s*(?:abstract\s+)?class\s+(\w+)/m', $content, $classMatch);
$className = $classMatch[1] ?? '';

メソッドの抽出

$pattern = '/(public|protected|private)\s+(static\s+)?function\s+(\w+)\s*\(([^)]*)\)/';
preg_match_all($pattern, $content, $matches, PREG_SET_ORDER);

foreach ($matches as $match) {
    $visibility = $match[1];  // public, protected, private
    $isStatic = !empty($match[2]);
    $methodName = $match[3];
    $params = $match[4];
}

PHPDocコメントの抽出

メソッド宣言の直前にあるPHPDocを取得するには、オフセットを使います。

preg_match_all($pattern, $content, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);

foreach ($matches as $match) {
    $methodOffset = $match[0][1];

    // メソッド宣言の前300文字を取得
    $before = substr($content, max(0, $methodOffset - 300), 300);

    // PHPDocブロックを抽出
    if (preg_match('/\/\*\*[\s\S]*?\*\/\s*$/s', $before, $docMatch)) {
        $docBlock = $docMatch[0];
    }
}

まとめ

正規表現を使えばPHPソースから構造情報を抽出できます。より正確な解析が必要な場合はnikic/php-parserの使用も検討してください。

カスタマイズに関するお問い合わせはこちら