Nguyen Thanh Nguyen Thanh - 7 months ago 21
PHP Question

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;

Answer

You can just explode it:

$string = 'reply-234-private';
$display = explode('-', $string);

var_dump($display);
> array(3) { [0]=> string(5) "reply" [1]=> string(3) "234" [2]=> string(7) "private" }

echo $display[1];
> 234

Or, use preg_match

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