supersize
supersize

Reputation: 14773

Cut string from end to specific char in php

I would like to know how I can cut a string in PHP starting from the last character -> to a specific character. Lets say I have following link:

www.whatever.com/url/otherurl/2535834

and I want to get 2535834

Important note: the number can have a different length, which is why I want to cut out to the / no matter how many numbers there are.

Thanks

Upvotes: 0

Views: 269

Answers (6)

hek2mgl
hek2mgl

Reputation: 157967

In this special case, an url, use basename() :

echo basename('www.whatever.com/url/otherurl/2535834');

A more general solution would be preg_replace(), like this:

                       <----- the delimiter which separates the search string from the remaining part of the string
echo preg_replace('#.*/#', '', $url);

The pattern '#.*/#' makes usage of the default greediness of the PCRE regex engine - meaning it will match as many chars as possible and will therefore consume /abc/123/xyz/ instead of just /abc/ when matching the pattern.

Upvotes: 1

divaka
divaka

Reputation: 593

Here's mine version:

$string = "www.whatever.com/url/otherurl/2535834";
echo substr($string, strrpos($string, "/") + 1, strlen($string));

Upvotes: 0

Suchit kumar
Suchit kumar

Reputation: 11859

if your pattern is fixed you can always do:

$str = 'www.whatever.com/url/otherurl/2535834';
$tmp = explode('/', $str);
echo $temp[3];

Upvotes: 0

Sergey Telshevsky
Sergey Telshevsky

Reputation: 12197

With strstr() and str_replace() in action

$str = 'www.whatever.com/url/otherurl/2535834';
echo str_replace("otherurl/", "", strstr($str, "otherurl/"));

strstr() finds everything (including the needle) after the needle and the needle gets replaced by "" using str_replace()

Upvotes: 0

Rizier123
Rizier123

Reputation: 59681

This should work for you:

(So you can get the number with or without a slash, if you need that)

<?php

    $url = "www.whatever.com/url/otherurl/2535834";
    preg_match("/\/(\d+)$/",$url,$matches);
    print_r($matches);

?>

Output:

Array ( [0] => /2535834 [1] => 2535834 )

Upvotes: 0

Pupil
Pupil

Reputation: 23958

Use

explode() AND end()

<?php
$str = 'www.whatever.com/url/otherurl/2535834';
$tmp = explode('/', $str);
echo end ($tmp);
?>

Working Demo

Upvotes: 0

Related Questions