「2個以上連続する半角スペース」を「半角スペースの数と同数の 」に置換する
<?php function replaceSpaces($input) { return preg_replace_callback('/ {2,}/', function($matches) { return str_repeat(' ', strlen($matches[0])); }, $input); } $input = "これは テスト です。"; $output = replaceSpaces($input); echo $output; ?>