$v) { $code .= ',' . $k . '=' . self::escape($v, true); } $code .= ']'; return $code; } /** * 反转义字符串中的CQ码敏感符号 * @param mixed $msg * @param mixed $is_content */ public static function decode($msg, $is_content = false) { $msg = str_replace(['&', '[', ']'], ['&', '[', ']'], $msg); if ($is_content) { $msg = str_replace(',', ',', $msg); } return $msg; } public static function replace($str) { $str = str_replace('{{', '[', $str); return str_replace('}}', ']', $str); } /** * 转义CQ码的特殊字符,同encode * @param mixed $msg * @param mixed $is_content */ public static function escape($msg, $is_content = false) { $msg = str_replace(['&', '[', ']'], ['&', '[', ']'], $msg); if ($is_content) { $msg = str_replace(',', ',', $msg); } return $msg; } /** * 转义CQ码的特殊字符 * @param mixed $msg * @param mixed $is_content */ public static function encode($msg, $is_content = false) { $msg = str_replace(['&', '[', ']'], ['&', '[', ']'], $msg); if ($is_content) { $msg = str_replace(',', ',', $msg); } return $msg; } /** * 移除消息中所有的CQ码并返回移除CQ码后的消息 * @param $msg * @return string */ public static function removeCQ($msg) { $final = ''; $last_end = 0; foreach (self::getAllCQ($msg) as $v) { $final .= mb_substr($msg, $last_end, $v['start'] - $last_end); $last_end = $v['end'] + 1; } $final .= mb_substr($msg, $last_end); return $final; } /** * 获取消息中第一个CQ码 * @param mixed $msg * @param mixed $is_object */ public static function getCQ($msg, $is_object = false) { if (($head = mb_strpos($msg, '[CQ:')) !== false) { $key_offset = mb_substr($msg, $head); $close = mb_strpos($key_offset, ']'); if ($close === false) { return null; } $content = mb_substr($msg, $head + 4, $close + $head - mb_strlen($msg)); $exp = explode(',', $content); $cq['type'] = array_shift($exp); foreach ($exp as $v) { $ss = explode('=', $v); $sk = array_shift($ss); $cq['params'][$sk] = self::decode(implode('=', $ss), true); } $cq['start'] = $head; $cq['end'] = $close + $head; return !$is_object ? $cq : CQObject::fromArray($cq); } return null; } /** * 获取消息中所有的CQ码 * @param mixed $msg * @param mixed $is_object */ public static function getAllCQ($msg, $is_object = false) { $cqs = []; $offset = 0; while (($head = mb_strpos(($submsg = mb_substr($msg, $offset)), '[CQ:')) !== false) { $key_offset = mb_substr($submsg, $head); $tmpmsg = mb_strpos($key_offset, ']'); if ($tmpmsg === false) { break; } // 没闭合,不算CQ码 $content = mb_substr($submsg, $head + 4, $tmpmsg + $head - mb_strlen($submsg)); $exp = explode(',', $content); $cq = []; $cq['type'] = array_shift($exp); foreach ($exp as $v) { $ss = explode('=', $v); $sk = array_shift($ss); $cq['params'][$sk] = self::decode(implode('=', $ss), true); } $cq['start'] = $offset + $head; $cq['end'] = $offset + $tmpmsg + $head; $offset += $head + $tmpmsg + 1; $cqs[] = (!$is_object ? $cq : CQObject::fromArray($cq)); } return $cqs; } }