duanhu7615 2014-10-10 02:13
浏览 25
已采纳

如何在视频游戏应用程序中将@提及语法转换为HTML?

I'm making a video game app that lets users @ mention a video game that is stored in the database. It works similar to the way you can @ mention users on Twitter, or @ mention anything on Facebook.

When the user types '@' when making a comment, JavaScript triggers a drop-down box to appear. The user selects a game from the drop-down box and when he selects it, it goes into the textarea. Internally, the string is stored using the format @[id:Game Title], which is a format I made up. So, if I want to @ mention "Super Mario Bros." in a comment I am making, the string stored internally (and sent to the database) would be:

@[6816:Super Mario Bros.] is a great game!

This format allows the application to know that the game ID is 6816, and that the game is "Super Mario Bros.".

When the comment displayed later, it needs to be in HTML format so that the user can click on the link to the game if he/she wants to. How would I use PHP to convert this raw string into HTML format, such as:

<a href="/games/6816">Super Mario Bros.</a> is a great game!

I have tried multiple solutions but none seem to work. I'm not sure if the best solution is to use regular expressions, or another solution. Keep in mind that a user can @ mention as many games as he/she so desires!

  • 写回答

1条回答 默认 最新

  • doume1301 2014-10-10 02:30
    关注

    Javascript

    var test = "@[6816:Super Mario Bros.] is a great game! @[6821:Super Mario Bros. 3] is fun too!";
    test.replace(/@\[(\d+?):(.+?)\]/g, "<a href=\"/games/$1\">$2</a>");
    

    PHP

    $test = '@[6816:Super Mario Bros.] is a great game! @[6821:Super Mario Bros. 3] is fun too!';
    preg_replace('/@\[(\d+?):(.+?)\]/', '<a href="/games/$1">$2</a>', $test);
    

    EDIT: Updated to support multiple tags

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题