简体   繁体   中英

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

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.

Use

explode() AND end()

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

Working Demo

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 )

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()

if your pattern is fixed you can always do:

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

Here's mine version:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM