php 如果定界符是字符串中的第一个字符,strtok 不起作用?

php strtok doesnt work if delimiter is a first character in the string?

我有一个可能包含或不包含特定分隔符的字符串列表,并使用 strtok 删除字符串中该分隔符之后的所有内容,例如:

$href = "test#content";
$href = strtok($href,'#');
echo $href;

输出:

test

我 运行 当字符串以定界符开头时出现问题:

$href = "#content";
$href = strtok($href,'#');
echo $href;

它输出的不是期望的 '' 输出:

content

为什么它的工作方式与第一个示例不同?用最少的额外代码获得所需结果的最有效方法是什么?

也许preg_split在这种情况下有用:

$href = "#content";
$pieces=preg_split('@#@',$href);
echo $pieces[0];/* Empty */
echo $pieces[1];/*content*/

如果你想要 return '#' 之前的所有内容,那么你可以使用 explode。

The behavior when an empty part was found changed with PHP 4.1.0. The old behavior returned an empty string, while the new, correct, behavior simply skips the part of the string.

测试 1 (https://3v4l.org/4lP5u):

$href = "#content";
$href = explode('#', $href);
echo $href['0'];

//returns ''

测试 2 (https://3v4l.org/ov9Yl):

$href = "test#content";
$href = explode('#', $href);
echo $href['0'];

//returns 'test'

编辑:

糟糕,我在 TEST 2 示例中添加了错误的 link,现在更新了 link。

根据您的评论

unfortunately I cant go explode route since $href variable will be reused later and cannot be array. Also, there is an incorrect output in the example in your second link because it echoes $href['1'] instead of $href['0']

你可以:

测试 3 (https://3v4l.org/uWPOk):

$href = "test#content";
$href = explode('#', $href);
$href = $href['0'];
echo $href;

测试 4 (https://3v4l.org/rtIJ0) :

这会检查字符串是否包含 # 并将其展开,否则 $href 保持不变

$href = "test#content";

if (strpos($href, '#') !== FALSE){
    $href = explode('#', $href);
    $href = $href['0'];
    echo $href;
}else{
    echo "$href";
}

我不认为 strtok 应该以这种方式使用...

在此处阅读手册http://php.net/manual/en/function.strtok.php

但我会使用这样的东西...

echo substr($href, 0, strpos($href, '#'));

如果您想要 # 之前的字符串,您应该使用 explode。您的方法的解决方法可能是这样的:

<?php 
$href = "#content";
if($href[0]=='#'){//check the first index character
    $href="''".$href;
}
$href = strtok($href,'#');
echo $href;

?>

在这种情况下,您可以使用 strstr(), for returning the left part of delimiter, when the third($before_needle) argument is passed, by default the right site is returned. To check if the delimiter exists or not you can use the preg_match() 来完成任务,它执行一个正则表达式,return true 如果模式是 find 或 false 则失败。

$href = "test#content";

if(preg_match('/#/', $href)){
    echo strstr($href, '#', true); //test
}else{
    echo 'delimiter not found';
}