duan0414 2014-12-04 17:34
浏览 115
已采纳

根据数组中的一个前缀将字符串分为两部分

So I have medical licenses that are kept as a string in the db. I need a way to show a license letter(s) (prefix) and number separately.

The array of prefixes is pre-defined:

$license_letters = array('20A', 'A', 'C', 'CNM', 'G', 'NP', 'PA');

And licenses look like 20A345000, C11006, G678999, PA200200, and so on. So I need to be able to get '20A' and '345000' or 'C' and '11006' for any license.

Searching by the first digit will not work because one of the possible prefixes is 20A. I'm pretty sure there must be a simple solution, but I can't think of it. Would appretiate any help.

  • 写回答

2条回答 默认 最新

  • doulin6088 2014-12-04 17:41
    关注

    If it is true that no license string is a part of any other (you don't have both "A" and "AB" in the list), then just loop through and find the first match as follows:

    function parts($licenseString) {
        $foreach($license_letters AS $prefix) {
            if(strpos($licenseString, $prefix) === 0) {
                return [$prefix, substr($licenseString, strlen($prefix)];
            }
        }
    }
    

    Edit: I meant to use === in the compare. strpos returns 'false' when no match is found, we want a match at position zero, hence we are looking for a return value which is specifically 0 (type number). Thanks for commenters pointing this out.

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

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)