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

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

我想获取字符串中第二个正斜杠之前的部分。假设我有一个名为

$hello
的字符串变量,它是:

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

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

$x = "hey/mate"

是的,我可以通过以下方式获取字符串的一部分,直到第一个斜杠(

/
):

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

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

php string sanitization truncation
3个回答
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"

0
投票

使用正则表达式提供了一种单函数解决方案,可以对其进行可变修改,以在字符或子字符串第 n 次出现时截断字符串。

如果您的定界子字符串 (

preg_quote()

) 不含需要正则表达式转义的字符,则不需要 
$marker
。包含此内容只是为了使该脚本可以作为通用辅助函数可靠地移植到现有应用程序。

(?:            # open a non-capturing group
   [^$char]*   # match zero or more non-marker characters 
   \K          # forget any previously matched characters
   $char       # match the marker character
)              # close the group
{{$nth}}       # require the nominated amount of repetitions of the non-capturing group
.*             # match zero or more characters to the end of the line

代码:(演示

function cutAtNthOf(string $text, string $char, int $nth): string
{
    $char = preg_quote($char);
    return preg_replace("#(?:[^$char]*\K$char){{$nth}}.*#", '', $text);
}
    
$test = 'hey/mate/from/outside//nothing';
for ($nth = 0; $nth <= 7; ++$nth) {
    echo cutAtNthOf($test, '/', $nth) . "\n";
}

输出:

hey
hey/mate
hey/mate/from
hey/mate/from/outside
hey/mate/from/outside/
hey/mate/from/outside//nothing
hey/mate/from/outside//nothing

此方法不会生成任何临时数组。随着所需重复次数的增加,无需进行额外的函数调用。

这种技术的好处是实用性、直接性和可变性。如果输入文本可能包含换行符,则在结束模式定界符后添加

s
,使模式中的
.
也匹配换行符。


在尝试使用

strtok()
复制我的脚本时,很明显,如果可能出现多个连续的分隔字符,则此本机函数不适合。 Demo 这是因为函数的“token”参数在一次执行中会消耗多个分隔符。此外,字符串开头的分隔字符将被忽略。请参阅文档中的特别说明


explode()
复制我的脚本并不可怕并且稳定。我只是发现当所需的结果字符串可以通过其他方式填充时,临时数组是间接编程。 演示

function cutAtNthOf(string $text, string $char, int $nth): string
{
    return implode(
        $char,
        array_slice(
            explode(
                $char,
                $text,
                $nth + 1
            ),
            0,
            $nth
        )
    );
}
© www.soinside.com 2019 - 2024. All rights reserved.