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 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用