Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP string echo the One thing before the end

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading