Home > Blockchain >  PHP string echo the One thing before the end
PHP string echo the One thing before the end

Time:12-19

my English is not good. sorry.

I want echo post_12345678 from my URL sting:

always want to echo the One thing before the end.

<?php
$url_string = "https://localhost/categories/post_12345678/a25d48aff";
echo preg_replace('/[\^categories/].*?[\/]/' , '', $string );
?>
  • a25d48aff and post_12345678 is Variable

CodePudding user response:

With parse_url, this task becomes much simpler. Just extract the value of the path key and access the second last key using explode and array_reverse.

<?php

$url_string = "https://localhost/categories/post_12345678/a25d48aff";

$str = trim(parse_url($url_string)['path'], '/');

echo array_reverse(explode("/", $str))[1];
  • Related