如何剪裁字符串从后面开始直到破折号?

时间:2013-05-20 09:06:17

标签: php regex

我想知道,如果我们可以修剪下面的字符串从后面开始直到破折号?

字符串

doc/20-05-2013_08-44-19_Rusly_60_sample1.pdf
doc/20-05-2013_08-44-19_Rusly_60_logo.png

输出

sample1.pdf
logo.png

9 个答案:

答案 0 :(得分:3)

简单地爆炸字符串并从数组中获取最后一个元素,如

$arr = explode("_", 'doc/20-05-2013_08-44-19_Rusly_60_sample1.pdf');
   echo end($arr);

答案 1 :(得分:3)

使用此

$str = "doc/20-05-2013_08-44-19_Rusly_60_sample1.pdf";
echo substr($str,strrpos($str,'_'));

答案 2 :(得分:2)

你可以这样解决:

echo array_pop(explode('_', $string));

答案 3 :(得分:1)

试试这个

$result = preg_replace('/(?m)^.+_(.+)$/', '$1', $subject);

答案 4 :(得分:1)

尝试strchr

$str = "doc/20-05-2013_08-44-19_Rusly_60_sample1.pdf";

echo substr(strrchr($str, "_"), 1);

答案 5 :(得分:0)

  1. 使用strrpos
  2. 找到破折号的位置
  3. 使用substr($ roginal,$ dashposition + 1)

答案 6 :(得分:0)

使用以下功能: http://php.net/manual/en/function.strrpos.php http://php.net/manual/en/function.substr.php

strrpos查看charachter的最后一次出现(例如它是_)当没有发现时,它返回false。 然后用substr得到字符串

然后代码将

$start = (strrpos('_', $string) !== false) ? strrpos($string) : 0;
$new_string = substr($string, $start);

答案 7 :(得分:0)

你可以这样做:

$value = array_pop( explode( "_", $yourVar) );
echo $value;

答案 8 :(得分:0)

我们应该计算最新破折号的位置吗? 如果doc/20-05-2013_08-44-19_Rusly_60_前缀长度恒定为33,该怎么办? 结果可能是samp_le1.pdf

echo substr( $str, 33 );