XMen
XMen

Reputation: 30238

How to get sub string in php

I have string http://mycloud.net/4d4bf89da2e38.jpg

I want 4d4bf89da2e38.jpg

How can i get this with php function or regexp.

Please Suggest.

Thanks

Upvotes: 0

Views: 386

Answers (6)

Smolla
Smolla

Reputation: 1751

Or you put sjmg answer in one line ;)

$name = array_pop(explode('/','http://mycloud.net/4d4bf89da2e38.jpg'));

Upvotes: 0

sjmg
sjmg

Reputation: 9

You don't need those functions, you only need to split the string.

$cadena='http://mycloud.net/4d4bf89da2e38.jpg';

$vec=explode("/",$cadena);

$name=array_pop($vec);

and you have the value in the variable $name

Upvotes: 0

rvs
rvs

Reputation: 1291

Use basename() function: http://php.net/manual/en/function.basename.php. It is probably faster then regexp and it would be cross-platform

Upvotes: 1

Russell Dias
Russell Dias

Reputation: 73282

Using basename() would probably be better in this case. But to answer your question title, you would use substr() to get a substring from a piece of text.

basename('http://mycloud.net/4d4bf89da2e38.jpg'); // returns 4d4bf89da2e38.jpg

Upvotes: 8

zerkms
zerkms

Reputation: 254906

$name = pathinfo('http://mycloud.net/4d4bf89da2e38.jpg', PATHINFO_BASENAME);

Upvotes: 4

Tim Pietzcker
Tim Pietzcker

Reputation: 336128

[^/]*$

will give you everything after the last slash.

In PHP:

if (preg_match('%[^/]*$%', $subject, $regs)) {
    $result = $regs[0];
} else {
    $result = "";
}

But isn't there a library available to deal with file paths?

Upvotes: 1

Related Questions