3

From the URL, let's say google.com/web1.php I would like to grab the part between the last slash and the extension, so: "web1" and then use it to point the specific image. Here is the example:

for url: google.com/web1.php

<img src="web1.jpg">

for url: google.com/web2.php

<img src="web2.jpg">

I know how to insert the whole URL, but don't know how to get a part of it. Here is what I use for the whole URL:

<img src="<?php echo "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; ?>.jpg"/>

How to get only the part I want instead of the whole URL? Thanks

1 Answer 1

1

If you print just:

echo  $_SERVER[REQUEST_URI];

It will print only the part you need.

Usually, the URI of a URL does not have the extension. In your case need to parse it.

echo preg_replace('/\\.[^.\\s]{3,4}$/', '', $_SERVER[REQUEST_URI]);

If you want to add the code on each php file, you could do this:

 echo pathinfo(__FILE__, PATHINFO_FILENAME);
Sign up to request clarification or add additional context in comments.

4 Comments

will it contain only the filename without the extension or domain name too? I need just a filename, as I will name .jpg's the same way as websites and will need to have a different jpg on each of pages.
Yes, that code only will have that. also if you have many PHP files, on each file you could make this: (see updated post)
Almost perfect, the only thing that needs tweaking is the last slash at the end. Currently it looks like this: <img src="web1/.jpg"> Can you help me get rid of the slash after the grabbed part? Thank you
echo pathinfo($_SERVER['REQUEST_URI'], PATHINFO_FILENAME);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.