0

I've created a function so I can display a specific part of a URL:

function PageName() {
return substr($_SERVER["REQUEST_URI"],strrpos($_SERVER["SCRIPT_NAME"],"/")+10,strrpos($_SERVER["SCRIPT_NAME"],"/")-4);
}

This will allow me to show The+Title if the URL is domain.com/my-pages/The+Title/go/

It works perfectly if the title is one word, but in the above example it is two words with a + sign.

I've tried to add str_replace("+"," ",PageName) at the end to replace the plus sign with an empty space, but doesn't seem to work:

function PageName() {
return substr($_SERVER["REQUEST_URI"],strrpos($_SERVER["SCRIPT_NAME"],"/")+10,strrpos($_SERVER["SCRIPT_NAME"],"/")-4,str_replace("+"," ",PageName));
}

Any ideas?

3
  • You are missing the third argument to str_replace. Commented Dec 23, 2016 at 16:16
  • My bad. Updated the original question. It's there but doesn't work still. Commented Dec 23, 2016 at 16:21
  • 1
    str_replace("+"," ",PageName()) - you need to call the function. I would actually do urldecode(PageName()) Commented Dec 23, 2016 at 16:26

1 Answer 1

3

For decoding the + you would better use urldecode, because that is what you are doing: decoding the URL format.

Furthermore, the +10 you have in the expression makes your solution not very reusable. Maybe you know at which position (counting forward slashes) that title is positioned at in the URL. In that case this might be more useful as a solution:

// $_SERVER["REQUEST_URI"] = "domain.com/my-pages/The+Title/go/";

function pageName($url) {
    return urldecode(explode("/", $url)[2]); // adapt the 2 to what you need.
}

echo pageName($_SERVER["REQUEST_URI"]);
Sign up to request clarification or add additional context in comments.

1 Comment

Genius! Works like a charm. Good note.

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.