从一个字符串中获取另一个字符串之后的内容

52

如何最快地从以下字符串中仅获取important_stuff部分:

bla-bla_delimiter_important_stuff

_delimiter_总是存在的,但字符串的其余部分可能会更改。


1
似乎存在一些混淆,不确定下划线是否真的存在。以下任何解决方案都可以。 - jon_darkstar
1
你可能会发现s($str)->afterFirst('_delimiter_')或者s($str)->afterLast('_delimiter_')很有用,这些函数可以在这个独立库中找到。 - caw
6个回答

78

这里:

$arr = explode('delimeter', $initialString);
$important = $arr[1];

8
在 PHP 5.4 版本中...特别是针对这种情况...您可以使用以下一行代码...$important = explode("delimeter",$initialString)[1]; 将初始字符串 $initialString 按照 "分隔符" 进行分割并获取第二个元素作为重要信息 $important - zgr024
3
当分隔符出现超过一次时,这个解决方案无法奏效。 - Robert
OP甚至没有说明在那种情况下所需的行为。因此,我们不知道它是否“有效”。 - jon_darkstar
如果只有一个分隔符,使用 limit 参数可能会更快:explode('delimiter', $initialString, 2) - 无需在其后遍历。 - user5147563
我建议这样做以避免警告: $important = isset($arr[1]) ? $arr[1] : ""; - Medhi

37
$result = end(explode('_delimiter_', 'bla-bla_delimiter_important_stuff'));

7
这会抛出一个错误:Strict Standards: Only variables should be passed by reference。你需要将explode()赋值给一个临时变量。 - Nikolay Mihaylov

8

我喜欢这种方法:

$str="bla-bla_delimiter_important_stuff";
$del="_delimiter_";
$pos=strpos($str, $del);

从分隔符结尾到字符串结尾的切割。
$important=substr($str, $pos+strlen($del)-1, strlen($str)-1);

注意:

1)对于substr函数,字符串从0开始;而对于strpos和strlen函数,字符串的长度从1开始。

2)使用一个字符作为分隔符可能是一个好主意。


6
$importantStuff = array_pop(explode('_delimiter_', $string)); 重要的是,这行代码将字符串按照“_delimiter_”分隔符进行拆分,并返回最后一个元素。

5
这会触发一个 E_STRICT 错误 (Strict Standards: Only variables should be passed by reference),因为 array_pop 使用了引用,但仍然可以工作。 - Martin Lyne

6
$string = "bla-bla_delimiter_important_stuff";
list($junk,$important_stufF) = explode("_delimiter_",$string);

echo $important_stuff;
> important_stuff

2
我喜欢使用列表。当你第一次使用数组时,我以为你向我展示了一种我不知道的类似Python的PHP能力! - jon_darkstar
我更喜欢这个答案,但有两点需要注意。1)在使用列表时,你不需要给出$junk变量 - list(,$important_stufF) = explode(...)就可以了。2)在PHP7的后续版本中,你可以使用更简洁的语法 - [,$important_stufF] = explode(...) - Barry

1
我作为一个正则表达式爱好者:
if (preg_match('/.*_delimiter_(.*)/', 'bla-bla_delimiter_important_stuff', $matches)) echo $matches[1];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接