首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何只在最后出现的分隔符上分解?

如何只在最后出现的分隔符上分解?
EN

Stack Overflow用户
提问于 2009-04-04 16:18:33
回答 11查看 23K关注 0票数 19
$split_point = ' - ';
$string = 'this is my - string - and more';

如何使用$split_point的第二个实例而不是第一个实例进行拆分。我能以某种方式指定从右到左的搜索吗?

基本上我是如何从右向左爆炸的。我只想拿起“-”的最后一个实例。

我需要的结果是:

$item[0]='this is my - string';
$item[1]='and more';

而不是:

$item[0]='this is my';
$item[1]='string - and more';
EN

回答 11

Stack Overflow用户

回答已采纳

发布于 2009-04-04 16:25:36

您可以使用strrev来反转字符串,然后反转结果:

$split_point = ' - ';
$string = 'this is my - string - and more';

$result = array_map('strrev', explode($split_point, strrev($string)));

不过,我不确定这是不是最好的解决方案。

票数 31
EN

Stack Overflow用户

发布于 2009-04-04 16:49:50

这样如何:

$parts = explode($split_point, $string);
$last = array_pop($parts);
$item = array(implode($split_point, $parts), $last);

不会赢得任何高尔夫奖项,但我认为它表现出了意图和良好的效果。

票数 12
EN

Stack Overflow用户

发布于 2012-04-20 17:12:55

这是另一种方法:

$split_point = ' - ';
$string = 'this is my - string - and more';

$stringpos = strrpos($string, $split_point, -1);
$finalstr = substr($string,0,$stringpos);
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/717328

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档