Search code examples
phpregexpreg-matchpcre

Get string between two strings


My string is: "reply-234-private", i want to get the number after "reply-" and before "-private", it is "234". I have tried with following code but it returns an empty result:

$string = 'reply-234-private';
$display = preg_replace('/reply-(.*?)-private/','',$string);
echo $display;

Solution

  • You can just explode it:

    <?php
    $string = 'reply-234-private';
    $display = explode('-', $string);
    
    var_dump($display);
    // prints array(3) { [0]=> string(5) "reply" [1]=> string(3) "234" [2]=> string(7) "private" }
    
    echo $display[1];
    // prints 234
    

    Or, use preg_match

    <?php
    $string = 'reply-234-private';
    if (preg_match('/reply-(.*?)-private/', $string, $display) === 1) {
        echo $display[1];
    }