B L Praveen
B L Praveen

Reputation: 2010

PHP Regex to get second occurance from the path

I have a path "../uploads/e2c_name_icon/" and I need to extract e2c_name_icon from the path. What I tried is using str_replace function

       $msg = str_replace("../uploads/","","../uploads/e2c_name_icon/");

This result in an output "e2c_name_icon/"

       $msg=str_replace("/","","e2c_name_icon/")

There is a better way to do this. I am searching alternative method to use regex expression.

Upvotes: 1

Views: 63

Answers (5)

Andreas
Andreas

Reputation: 23968

You can trim after the str_replace.

echo $msg = trim(str_replace("../uploads/","","../uploads/e2c_name_icon/"), "/");

I don't think you need to use regex for this. Simple string functions are usually faster

You could also use strrpos to find the second last /, then trim off both /.

$path = "../uploads/e2c_name_icon/";
echo $msg = trim(substr($path, strrpos($path, "/",-2)),"/");

I added -2 in strrpos to skip the last /. That means it returns the positon of the / after uploads.
So substr will return /e2c_name_icon/ and trim will remove both /.

Upvotes: 1

Dylan KAS
Dylan KAS

Reputation: 5713

If you are strictly want to get the last part of the url after '../uploads'

Then you could use this :

$url = '../uploads/e2c_name_icon/';
$regex = '/\.\.\/uploads\/(\w+)/';
preg_match($regex, $url, $m)
print_r ($m); // $m[1] would output your url if possible

Upvotes: 1

ascsoftw
ascsoftw

Reputation: 3476

Use basename function provided by PHP.

 $var = "../uploads/e2c_name_icon/";
 echo basename( $var ); // prints e2c_name_icon

Upvotes: 1

Ro Achterberg
Ro Achterberg

Reputation: 2714

Try this. Outputs: e2c_name_icon

<?php

$path = "../uploads/e2c_name_icon/";

// Outputs: 'e2c_name_icon'
echo explode('/', $path)[2];

However, this is technically the third component of the path, the ../ being the first. If you always need to get the third index, then this should work. Otherwise, you'll need to resolve the relative path first.

Upvotes: 2

atymic
atymic

Reputation: 3128

You'd be much better off using the native PHP path functions vs trying to parse it yourself.

For example:

$path = "../uploads/e2c_name_icon/";

$msg = basename(dirname(realpath($path))); // e2c_name_icon

Upvotes: 0

Related Questions