Home >Backend Development >PHP Tutorial >如何从右边向左截取字符串

如何从右边向左截取字符串

WBOY
WBOYOriginal
2016-06-23 14:23:131557browse

本帖最后由 goolean 于 2013-09-30 21:31:47 编辑

字符串为:"。。还有很多。。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可以用负数是正解

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn