[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 185
  • Last Modified:

URL directory echo

I need extract few directories from URL except first one if length = 2, for example:

experts-exchange.com/WD/Web_Languages-Standards/PHP/newQuestionWizard.jsp

I need to only bold part and ignore first directory as it's length equal 2;

experts-exchange.com/Web_Development/Web_Languages-Standards/PH/newQuestionWizard.jsp

I need all directories as first one isn't equal 2, and it doesn't matter what length of others.
0
SSupreme
Asked:
SSupreme
  • 4
  • 4
1 Solution
 
käµfm³d 👽Commented:
How about this:
$result = preg_replace('#^[^/]*|[^/]*$#', '', $input);
$result = preg_replace('#^/?[^/]{2}(?=/)#', '', $result);

var_dump($result);

Open in new window

0
 
käµfm³d 👽Commented:
This version accounts for the scheme also:

$result = preg_replace('#^(?:[^:]+://)?[^/]*|[^/]*$#', '', $input);   // Remove leading scheme and host
$result = preg_replace('#^/?[^/]{2}(?=/)#', '', $result);             // Remove first dir if it's 2 characters

Open in new window

0
 
SSupremeAuthor Commented:
Excuse me, which scheme?
0
 [eBook] Windows Nano Server

Download this FREE eBook and learn all you need to get started with Windows Nano Server, including deployment options, remote management
and troubleshooting tips and tricks

 
käµfm³d 👽Commented:
Scheme as in "http:", "ftp:", "gopher:", etc. I didn't know if you had this (your example doesn't show it), but I included it just in case.
0
 
SSupremeAuthor Commented:
ok it works 100%, I guess it was easy for you, so could you please suggest how to show name of directory if it's first and length = 2.
0
 
SSupremeAuthor Commented:
You are Genius Indeed, thanks
0
 
käµfm³d 👽Commented:
so could you please suggest how to show name of directory if it's first and length = 2.
If I understand your question correctly, then I believe what you could do would be to change the second preg_replace to:

preg_match('#^(/?[^/]{2}(?=/))?(.*)$#', $result, $matches);             // Remove first dir if it's 2 characters

Open in new window


You would have the 2-character directory (or empty string) in the second index of $matches, and you would have the remaining directories in the third index. In other words:

var_dump($matches[1]);  // 2-character directory (or empty string)
var_dump($matches[2]);  // Remaining directories

Open in new window

0

Featured Post

Fill in the form and get your FREE NFR key NOW!

Veeam is happy to provide a FREE NFR server license to certified engineers, trainers, and bloggers.  It allows for the non‑production use of Veeam Agent for Microsoft Windows. This license is valid for five workstations and two servers.

  • 4
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now