php代码
<?php /** *MentionModel.class.php */ class mentionModel extends Model{ private $userList; //存放最近一次提取到提及用户列表 /** * 提取@信息,添加链接,并插入mention数据库 * @param $content 需要提取的文本 * @param $isConstructUrl,是否构造url,转发的话不需要再次构造url * @param $isConstructTag,是否构造Tag * @return string 返回构造好的文本 */ public function convertContent($content ,$isConstructUrl = TRUE ,$isConstructTag = TRUE){ $mentionDb = M("mention"); $userDb = M("account_users"); $content = $content.' '; //防止最后有@,后面会去掉 $pattarn = '#@(.*)\s#U'; $match = array(); //获取用户昵称 preg_match_all($pattarn , $content , $match); //构造查询条件 $userIn = ''; foreach ($match[1] as $matchTemp){ $userIn .= $matchTemp.','; } $userIn = substr($userIn, 0 , strlen($userIn)-1); $map['nicename'] = array('in',$userIn); //获取对用用户 $this->userList = $userDb->field('account_id,nicename')->where($map)->select(); //合并数组,方便操作 $userListGroup = array(); foreach($this->userList as $userListTemp){ $userListGroup[$userListTemp['account_id']] = $userListTemp['nicename']; } //生成替换格式 if($isConstructUrl){ $replaceArr = array(); foreach($userListGroup as $account_id =>$nicename){ $replace = $this->_constructUrl($account_id,$nicename); $replaceArr += array("@".$nicename.' ' => $replace ); //这里空格也替换 } //替换 $content = strtr($content,$replaceArr); } //标签处理 $tagPattarn = '/#(.*)#/U'; $tagMatch = array(); //是否需要格式化标签 if($isConstructTag && preg_match_all($tagPattarn , $content , $tagMatch) ){ $tagIn = ''; $tagReplacArr = array(); foreach ($tagMatch[1] as $tagTmp){ if($constructTmp = $this->_constructTag($tagTmp)){ $tagReplacArr += array('#'.$tagTmp.'#' => $constructTmp); } } //替换 $content = strtr($content,$tagReplacArr); } return $content; } /** * 格式提及用户,格式未定。 * @param $account_id * @param $nicename * @return string 返回格式的的用户链接 */ private function _constructUrl($account_id,$nicename){ return '<a href="account_id/'.$account_id.'">@'.$nicename.' </a>'; } /** * 格式提及标签,格式未定。 * @param $tagName 标签名 * @return boolean|string 返回格式的的标签 */ private function _constructTag( $tagName ){ /*不需查询数据库, $tagDb = M('tages_info '); $map['cnname'] = $tagName; $map['enname'] = $tagName; $map['_logic'] = 'OR'; if(! $tag = $tagDb->where($map)->field("tage_id")->find()){ //没有该标签 return false; } */ return '<a href="search/' . $tagName .'">#' . $tagName . '#</a>'; } /** * 添加到提及数据库,暂未完成 */ public function addToMention($type , $id){ if(! $this->userList || !$type || !$id){ return false; } dump($this->userList); } } class TestAction extends Action { public function index(){ $mentionDb = D("mention"); $content = "#百搭#@ @小红 @小明 @sdfklj @dsf #英伦##英伦##英伦# #english##英伦##sdf#"; //构造content $content = $mentionDb->convertContent($content , true , true); echo $content; //......将分享或评论什么的插入数据库,并获取其id $id与对应类别 $type $type = 2; //假设类别为2 $id = 1;//假设插入数据库的分享或评论的id为1 $mentionDb->addToMention($type,$id); } }