Extract a substring between two characters in a string PHP

前端 未结 10 1457
逝去的感伤
逝去的感伤 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 22:57

    Use:

    <?php
    
    $str = "[modid=256]";
    $from = "=";
    $to = "]";
    
    echo getStringBetween($str,$from,$to);
    
    function getStringBetween($str,$from,$to)
    {
        $sub = substr($str, strpos($str,$from)+strlen($from),strlen($str));
        return substr($sub,0,strpos($sub,$to));
    }
    
    ?>
    
    0 讨论(0)
  • 2020-12-02 23:00

    use this code

    $input = "[modid=256]";
    preg_match('~=(.*?)]~', $input, $output);
    echo $output[1]; // 256
    

    working example http://codepad.viper-7.com/0eD2ns

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

    Regular Expression is your friend.

    preg_match("/=(\d+)\]/", $String, $matches);
    var_dump($matches);
    

    This will match any number, for other values you will have to adapt it.

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

    Try Regular Expression

    $String =" [modid=256]";
    $result=preg_match_all('/(?<=(=))(\d+)/',$String,$matches);
    print_r($matches[0]);
    

    Output

    Array ( [0] => 256 )

    DEMO

    Explanation Here its used the Positive Look behind (?<=)in regular expression eg (?<=foo)bar matches bar when preceded by foo, here (?<=(=))(\d+) we match the (\d+) just after the '=' sign. \d Matches any digit character (0-9). + Matches 1 or more of the preceeding token

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

    (moved from comment because formating is easier here)

    might be a lazy approach, but in such cases i usually would first explode my string like this:

    $string_array = explode("=",$String); 
    

    and in a second step i would get rid of that "]" maybe through rtrim:

    $id = rtrim($string_array[1], "]");
    

    ...but this will only work if the structure is always exactly the same...

    -cheers-

    ps: shouldn't it actually be $String = "[modid=256]"; ?

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

    If you don't want to use reqular expresion, use strstr, trim and strrev functions:

    // Require PHP 5.3 and higher
    $id = trim(strstr(strstr($String, '='), ']', true), '=]');
    
    // Any PHP version
    $id = trim(strrev(strstr(strrev((strstr($String, '='))), ']')), '=]');
    
    0 讨论(0)
提交回复
热议问题