dongyuqi3808 2012-08-08 04: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 04: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部