Get string between two strings

Thanh Nguyen picture Thanh Nguyen · Jan 14, 2013 · Viewed 43.8k times · Source

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;

Answer

sachleen picture sachleen · Jan 14, 2013

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];
}