我的目标是检查消息是否有表情符号,如果是,我将转换它们。 我在找出字符串中有多少表情符号时遇到问题。
例:
$string = ":+1::+1::+1:"; //can be any string that has :something: between ::
这里的目标是获得:+1:(全部(,但我尝试了两种模式,但我一直只得到 1 匹配。
preg_match_all('/:(.*?):/', $string, $emojis, PREG_SET_ORDER); // $emojis is declared as $emojis='' at the beginning. preg_match_all('/:(S+):/', $string, $emojis, PREG_SET_ORDER);
获得匹配后其余代码
我正在这样做:
if (isset($emojis[0]))
{
$stringMap = file_get_contents("/api/common/emoji-map.json");
$jsonMap = json_decode($stringMap, true);
foreach ($emojis as $key => $value) {
$emojiColon = $value[0];
$emoji = key_exists($emojiColon, $jsonMap) ? $jsonMap[$emojiColon] : '';
$newBody = str_replace($emojiColon, $emoji, $newBody);
}
}
我将不胜感激任何帮助或建议,谢谢。
我稍微更新了一下你的表达:
preg_match_all('/:(.+?)(:)/', $string, $emojis, PREG_SET_ORDER);
echo var_dump($emojis);
:
现在已转义,否则可能会被视为特殊字符。- 将
*
替换为+
,这样您就不会匹配两个连续的::
,但中间至少需要一个字符。