<?php

class Markdown
{

	static function processing($string)
	{
		$string = self::replaceHeaders($string);
		$string = self::replaceBold($string);
		$string = self::replaceItalic($string);
		$string = self::replaceUnderline($string);
		$string = self::replaceChars($string);
		$string = self::replaceUrls($string);

		return $string;
	}

	static private function replaceHeaders($string)
	{
		for ($index = 3; $index > 0; $index--) {

			$pr = '/(^#{' . $index . '} .{1,})/m';

			preg_match_all($pr, $string, $headers);

			if (isset($headers[0][0])) {
				foreach ($headers[0] as $header) {
					$hI = $index+1;
					$string = str_replace($header, "<h$hI>" . mb_substr($header, $index + 1, NULL, 'UTF-8') . "</h$hI>", $string);
				}
			}
		}

		return $string;
	}

	static private function replaceBold($string)
	{
		$pr = '(\*{2}(.+?)\*{2})';
		$rep = '<b>$1</b>';
		return preg_replace($pr, $rep, $string);
	}

	static private function replaceItalic($string)
	{
		$pr = '(\*{1}(.+?)\*{1})';
		$rep = '<i>$1</i>';
		return preg_replace($pr, $rep, $string);
	}

	static private function replaceUnderline($string)
	{
		$pr = '(\_{1}(.+?)\_{1})';
		$rep = '<u>$1</u>';
		return preg_replace($pr, $rep, $string);
	}

	static private function replaceUrls($string)
	{
		$pr = '((https{0,1}:\/\/[\da-z\.-]+\.[a-z]{2,6})[\/\w\?=&#%+\.,-]*\/?)';
		$rep = '<a href="$0" title="$0" target="_blank">$1</a>';
		return preg_replace($pr, $rep, $string);
	}

	static private function replaceChars($string)
	{
		$pr = '((^|\s)-{2}($|\s))';
		$rep = '$1–$2';
		$string = preg_replace($pr, $rep, $string);

		$pr = '((^|\s)\((c|с)\)($|\s))';
		$rep = '$1©$3';
		$string = preg_replace($pr, $rep, $string);

		$string = str_replace(
				array("\r", '"', '«', '»'),
				array('', 'ʺ', 'ʺ', 'ʺ'),
				$string);

		return $string;
	}

	static function getClear($string)
	{
		// Headers
		for ($index = 3; $index > 0; $index--) {

			$pr = '/(^#{' . $index . '} .{1,})/m';

			preg_match_all($pr, $string, $headers);

			if (isset($headers[0][0])) {
				foreach ($headers[0] as $header) {
					$hI = $index+1;
					$string = str_replace($header, '', $string);
				}
			}
		}

		// Bold & Italic
		$pr = '(\*{1,3}(.+?)\*{1,3})';
		$rep = '$1';
		$string = preg_replace($pr, $rep, $string);

		// Uderline
		$pr = '(\_{1}(.+?)\_{1})';
		$rep = '$1';
		$string = preg_replace($pr, $rep, $string);

		// Images
		$pr = '(\[img[\|]#(\d+)\])';
		$rep = ' ';
		$string = preg_replace($pr, $rep, $string);

		// \n & \r
		$string = str_replace(array("\n","\r",' -- '), array(' ', ' ',' – '), $string);

		// URL
		$pr = '((https{0,1}:\/\/[\da-z\.-]+\.[a-z]{2,6})[\/\w\?=&#%+\.,-]*\/?)';
		$rep = '';
		$string = preg_replace($pr, $rep, $string);

		// Points
		$pr = '((\[#(\d+)[>\|](.*?)\])|(\[#(\d+)\]))';
		$rep = ' ';
		$string = preg_replace($pr, $rep, $string);

		// multi-space
		$pr = '(\s{2,})';
		$rep = ' ';
		$string = preg_replace($pr, $rep, $string);

		return trim($string);
	}

}
