dongyuqi3808 2012-08-08 12:17
浏览 79
已采纳

从字符串中获取所需的子字符串

How do I get substring from string which start with s and end with /s.

$text can be in following formats

 $text = "LowsABC/s";
 $text = "sABC/sLow";
 $text = "ABC";

how can I get ABC, sometime it may happen that $text does not contain s and /s just only ABC, Still I want to get the ABC.

  • 写回答

2条回答 默认 最新

  • dongquanjie9328 2012-08-08 12:20
    关注

    The regular expression:

    s(.*)/s
    

    Or when you want to get a string of minimal length:

    s(.*?)/s
    

    And apply this res you can using preg_match:

    preg_match( '@s(.*)/s@', $text, $match );
    var_dump( $match );
    

    And now you must check, if something was found or not, and if not, then the result must be set to the entire string:

    if (not $match) {
       $match = $text;
    }
    

    Example of usage:

    $ cat 1.php 
    <?
    $text = "LowsABC/s";
    preg_match( '@s(.*)/s@', $text, $match );
    var_dump( $match );
    ?>
    
    $ php 1.php
    array(2) {
      [0]=>
      string(6) "sABC/s"
      [1]=>
      string(3) "ABC"
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于这个问题的解释说明
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。