dongmaoxi0477 2015-04-02 16:41
浏览 48
已采纳

substr在通配符子字符串之前查找所有文本

What I am trying to do is get all of the characters before a wildcard substring. For example, if I have the following string:

I.Want.This.Bit.D00F00.Non.Of.This

So, I want the output to be I.Want.This.Bit

The D and the F in D00F00 are always going to be there, but the integers inbetween will change. So it could be D13F02, or D01F15. The will not be more than 2 integers after the D and the F.

I had thought about doing the following, but then realised it would not work:

$string = "I.Want.This.Bit.D00F00.Non.Of.This"    
$substring = substr($string, 0, strpos($string, '.D'));

The reason it would not work is because there is a chance the bit of the string I want to keep could have a .D in it, e.g The.Daft.String.D03F12. Using that example, all I would get is The as the output, rather than The.Daft.String.

Any guidance would be much appreciated.

  • 写回答

4条回答 默认 最新

  • doutanghuan9595 2015-04-02 16:52
    关注

    Probably best to use preg_match for this since you want to capture a specific part of the string. Use regex capturing group.

    <?php
    
    $pattern = "/^([A-Za-z\.]+)\.D[0-9]{2}F[0-9]{2}/";
    $subject = "I.Want.This.Bit.D00F00.Non.Of.This";
    
    preg_match($pattern, $subject, $matches);
    print_r($matches);
    

    In this case the captured group you want will be in $matches[1].

    You can play with/test the regex here: https://regex101.com/r/sM4wN9/1

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

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!