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

时间:2015-11-30 12:58:34

标签: php replace strtok

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

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

输出:

test

当字符串以分隔符开头时,我遇到了一个问题:

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

而不是所需的''输出,它输出:

content

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

5 个答案:

答案 0 :(得分:3)

在这种情况下,您可以使用strstr()来返回分隔符的左侧部分,当传递第三个($before_needle)参数时,默认情况下会返回正确的站点。要检查分隔符是否存在,您可以使用preg_match()执行任务,它可以执行正则表达式,如果模式为find则返回true,如果失败则返回false。

$href = "test#content";

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

答案 1 :(得分:2)

如果您想在“#”之前退回所有内容,则可以使用“爆炸”。

  

发现空白部分的行为随PHP 4.1.0而改变。该   旧行为返回一个空字符串,而新的,正确的,   行为只是跳过字符串的一部分。

TEST 1 https://3v4l.org/4lP5u):

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

//returns ''

TEST 2 https://3v4l.org/ov9Yl):

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

//returns 'test'

<强> 修改

WHOOP我在TEST 2示例中添加了错误的链接,现在更新了链接。

根据你的评论

  

不幸的是,我不能去爆炸路线,因为$ href变量将是   以后重用,不能是数组。此外,输出不正确   在第二个链接的示例中,因为它回显了$ href ['1']   而不是$ href ['0']

你可以:

TEST 3 https://3v4l.org/uWPOk):

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

TEST 4 https://3v4l.org/rtIJ0):

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

$href = "test#content";

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

答案 2 :(得分:1)

在这种情况下,preg_split可能会有用:

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

答案 3 :(得分:0)

我认为strtok不会被这样使用......

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

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

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

答案 4 :(得分:0)

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

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

?>