dop83362 2011-04-20 09:09
浏览 41
已采纳

过滤mysql搜索的文本

I am new to regex and really don't have a clue. I have a MySql table looking like this:

id | grade | subject | kind | tally
1  | 11    | M       | L    | 1
2  | 11    | E       | L    | 3
3  | 11    | D       | G    | 1
4  | 11    | GK      | G    | 1
5  | 11    | SPA     | G    | 6

you get the idea...:)

Grade is an int, either 11,12 or 13. Subject is a string, between 1-4 "chars" long. Kind is either "L" or "G". Tally is an int, between 1 and 6.

This table is supposed to hold all of the classes/lessons there are at my school. When you write out the classname it would look something like this "11EL4" or "11ML1".

I want to be able to turn this "description" into grade, subject, kind and tally. For example:

function descriptionToArray($description){
    // $grade   = regex voodoo :)
    // $subject = regex voodoo :)
    // ...

    return array("grade"=>$grade,"subject"=>$subject,...);
}

My guess would have been regex but I really don't know how that works (even after tutorials)

  • 写回答

3条回答 默认 最新

  • douzai8285 2011-04-20 09:24
    关注

    Try this:

    if (preg_match('/(11|12|13)([A-Z]{1-4})(L|G)([1-6]{1})/', $class_string, $match)) {
        list($dummy, $grade, $subject, $kind, $tally) = $match;
    }
    

    Explanation:

    • (11|12|13) matches 11, 12 or 13
    • ([A-Z]+?) matches 1 or more capital letters (ungreedy)
    • (L|G) matches an L or a G
    • ([1-6]{1}) matches a single digit in the range 1-6

    The $dummy is required because $match[0] will hold the entire regular expression match. Elements 1-4 will hold each patenthesised substring.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障
  • ¥15 opencv 无法读取视频