如果分隔符是字符串中的第一个字符,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

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

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

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

如果要返回'#'之前的所有内容,则可以使用爆炸。

PHP 4.1.0更改了发现空部件时的行为。这个旧的行为返回一个空字符串,而新的、正确的、,行为只是跳过字符串的一部分。

测试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'

编辑

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

根据您的意见

很遗憾,由于$href变量将为以后重复使用,不能作为数组。此外,输出不正确在第二个链接中的示例中,因为它与$href['1']相呼应而不是$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";
}

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

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

我不认为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;
?>