<?php
/**************************************************
*  Created:  2010-06-08
*
*  格式化微博显示的内容
*
*  @Xweibo (C)1996-2099 SINA Inc.
*  @Author xionghui <xionghui1@staff.sina.com.cn>
*
***************************************************/

function format_text($text, $type = 'feed')
{
	if (!empty($text)) {
		if ($type == 'feed') {
			$matches = array();
			//如果微博内容的话题本身新浪微博的连接就不替换 
			if (preg_match("#<a href=['\"]http://t.sina.com.cn/(.*)['\"]\s?(target='_blank'){0,1}>.+</a>#", $text)) {
//				$text = htmlspecialchars($text);
			} elseif (!preg_match('#<a href="(http://t.sina.com.cn/k/(.+))">.+</a>#', $text, $matches)) {
				$match_text = $text;
				//如果微博内容的话题本身已经是连接，则只替换连接地址
				$text = htmlspecialchars($text);

				//替换url
				$matches = array();
				preg_match_all('#http://[^\x{4e00}-\x{9fa5}"\s]+\.[^\x{4e00}-\x{9fa5}"\>[\s]+#u', $match_text, $matches);
				if (!empty($matches)) {
					$matches[0] = array_unique($matches[0]);
					foreach ($matches[0] as $var) {
						$search_url[] = $var;
						$replace_url[] = ' <a title="'.$var.'" href="'.$var.'" target="_blank">'.$var.'</a> ';
					}
					$text = str_replace($search_url, $replace_url, $text);
				}

				//替换话题
				$matches = array();
				preg_match_all('/#([^#]+?)#/', $text, $matches);
				if (!empty($matches)) {
					foreach ($matches[0] as $key => $var) {
						if (empty($matches[1][$key])) {
							continue;
						}
						$search[] = $var;
						$replace[] = ' <a href="'.URL('search', array('k' => $matches[1][$key])).'">'.$var.'</a> ';
					}
					$text = str_replace($search, $replace, $text);
				}
			} else {
				$text = str_replace($matches[1], URL('search', array('k' => $matches[2])), $text);
			}

			//替换@
			if (!preg_match('/\w+(@\w*\.)*\w+@\w+(\.\w+)+/', $text)) {
				$matches = array();
				preg_match_all('/@([\x{4e00}-\x{9fa5}0-9A-Za-z_]+)/u', $text, $matches);
				if (!empty($matches)) {
					foreach ($matches[0] as $key => $var) {
						$search[] = $var;
						$replace[] = '<a href="'.URL('ta', array('name' => $matches[1][$key])).'">'.$var.'</a>';
					}
					$text = str_replace($search, $replace, $text);
				}
			}
		} else {
			$text = htmlspecialchars($text);
		}

		//替换表情
		$emoticons = V('-:sinaWeiboEmotions');
		foreach ($emoticons as $var) {
			$search_em[] = '['.$var[0].']';
			$replace_em[] = '<img title="'.$var[0].'" src="'.WB_EMOTICONS_URL.$var[1].'">';
		}
		$text = str_replace($search_em, $replace_em, $text);

		//$text = str_replace(array("\r\n", "\r", "\n"), ' ', $text);
	}
	return $text;
}
?>

