Extract a substring between two characters in a string PHP

前端 未结 10 1458
逝去的感伤
逝去的感伤 2020-12-02 22:38

Is there a PHP function that can extract a phrase between 2 different characters in a string? Something like substr();

Example:

$String          


        
相关标签:
10条回答
  • 2020-12-02 23:18
    $str = "[modid=256]";
    preg_match('/\[modid=(?P<modId>\d+)\]/', $str, $matches);
    
    echo $matches['modId'];
    
    0 讨论(0)
  • 2020-12-02 23:19

    You can use a regular expression:

    <?php
    $string = "[modid=256][modid=345]";
    preg_match_all("/\[modid=([0-9]+)\]/", $string, $matches);
    
    $modids = $matches[1];
    
    foreach( $modids as $modid )
      echo "$modid\n";
    

    http://eval.in/9913

    0 讨论(0)
  • 2020-12-02 23:21

    You can use a regular expression or you can try this:

    $String = "[modid=256]";
    
    $First = "=";
    $Second = "]";
    $posFirst = strpos($String, $First); //Only return first match
    $posSecond = strpos($String, $Second); //Only return first match
    
    if($posFirst !== false && $posSecond !== false && $posFirst < $posSecond){
        $id = substr($string, $First, $Second);
    }else{
    //Not match $First or $Second
    }
    

    You should read about substr. The best way for this is a regular expression.

    0 讨论(0)
  • 2020-12-02 23:22
    $String = "[modid=256]";
    
    $First = "=";
    $Second = "]";
    
    $Firstpos=strpos($String, $First);
    $Secondpos=strpos($String, $Second);
    
    $id = substr($String , $Firstpos, $Secondpos);
    
    0 讨论(0)
提交回复
热议问题