在字符第二次出现时截断字符串

问题描述 投票:0回答:2

我想获取第二个正斜杠之前的字符串部分。好吧,为了简单起见,我可以说我有一个名为 hello 的字符串,它是:

$hello = "hey/mate/from/outside/nothing/is/to/be/done";

如何获取字符串到第二个斜杠的部分,使其成为

$x = "hey/mate"

是的,我可以获取第一个斜线 / 之前的部分字符串

$x = strtok($hello,  '/');

我尝试搜索类似的功能但找不到。

有什么功能可以使用吗? 那么我们可以获取到第二个斜杠之前的部分字符串吗?

php string sanitization truncation
2个回答
3
投票

用 / 分解字符串并做你想做的事。试试这个

$hello="hey/mate/from/outside/nothing/is/to/be/done";
$a=explode('/',$hello);// returns an array 
echo $a[0]."/".$a[1];

0
投票

strtok
跟踪它分解的字符串,因此您可以按照文档中的描述使用它

$str = "hey/mate/from/outside/nothing/is/to/be/done";

$first = strtok($str, "/");
$second = strtok("/");

echo "$first/$second"; // "hey/mate"
© www.soinside.com 2019 - 2024. All rights reserved.