Extract a substring between two characters in a string PHP

前端 未结 10 1499
逝去的感伤
逝去的感伤 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: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.

提交回复
热议问题