<?php

error_reporting(-1);
mb_internal_encoding('utf-8');

$text = "ну что.      не смотрел еще black mesa.я собирался скачать  ,но все как-то некогда было.";
// Для тестов
// $text = 'roses are red,and violets are blue.whatever you do i'll keep it for you.';
// $text = 'привет.есть 2 функции,preg_split и explode ,не понимаю,в чем между ними разница.';

/* исправляет текст */
function fixText($text) {
	$regexp = "/(\\s+)?(,|[.!?])(\\s+)?/u";
	$temp = preg_replace($regexp, "$2 ", $text);
	$temp = trim($temp);
	
	$temp = preg_split("//u", $temp, null, PREG_SPLIT_NO_EMPTY);
	$temp[0] = mb_strtoupper($temp[0]);
	for ($i = 0; $i < (count($temp) - 2); $i++) {
		if (($temp[$i] == "." || $temp[$i] == "!" || $temp[$i] == "?") && ($temp[$i + 1] == " ")){
			$temp[$i + 2] = mb_strtoupper($temp[$i + 2]);
		}
	}
	$temp = implode($temp);
	
	return $temp;
}

$result = fixText($text);
echo "{$result}\n";
