Heim >Backend-Entwicklung >PHP-Tutorial >如何从右边向左截取字符串
字符串为:"。。还有很多。。001_002_003",想要从右边第4个(_003)开始,得到向左的所有字符串“。。还有很多。。001_002"
substr可以用负数,详情参考:
http://cn2.php.net/manual/zh/function.substr.php
可以使用"_"作为分割符,数组操作。
[code=php][ $str='001_002_003';
$find='_003';
echo substr($str,0,strpos($str,$find))
?>/code]
<?php$str='001_002_003';$find='_003';echo substr($str,0,strpos($str,$find))?>
$s = '001_002_003';echo substr($s, 0, -4);//001_002echo substr($s, 0, strrpos($s, '_'));//001_002echo join('_', array_slice(explode('_', $s), 0, -1));//001_002echo strrev(substr(strrev($s), 4));//001_002
$str = '001_002_003';$data = explode('_',$str);krsort($data);foreach($data as $row)echo $row.'<br>';
$str = '001_002_003_004_005_006_007';$data = explode('_',$str);krsort($data);$total = count($data);$need = $total - 3;foreach($data as $k=>$row){ if($k<$need){ echo $row.'<br>'; }}
没看清题目,6楼的不算,7楼的应该是LZ要求的条件吧?
参考:
<?php$rest = substr("abcdef", 0, -1); // 返回 "abcde"$rest = substr("abcdef", 2, -1); // 返回 "cde"$rest = substr("abcdef", 4, -4); // 返回 ""$rest = substr("abcdef", -3, -1); // 返回 "de"?>
substr可以用负数是正解