简体   繁体   English

在PHP中将字符串从结尾切成特定字符

[英]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. 我想知道我怎么能切string在PHP从最后一个字符开始- >到一个特定的字符。 Lets say I have following link: 可以说我有以下链接:

www.whatever.com/url/otherurl/2535834

and I want to get 2535834 我想要得到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() : 在这种特殊情况下,使用url可以使用basename()

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

A more general solution would be preg_replace() , like this: 更通用的解决方案是preg_replace() ,如下所示:

                       <----- 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. 模式'#。* /#'使用PCRE regex引擎的默认贪婪性-意味着它将匹配尽可能多的字符,因此在匹配时将使用/abc/123/xyz/而不是/abc/图案。

Use 采用

explode() AND end() explode()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 使用strstr()str_replace()

$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() 在使用str_replace()并将针替换为“”之后, strstr()查找所有内容(包括针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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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