doze79040 2014-11-30 07:20
浏览 64
已采纳

PHP strtok()如果我理解这一点,请告诉我

This is the the code:

<?php
    $string = 'Hey there buddy';
    $token = strtok($string, ' ');
    while($token !== false)
    {
        echo $token."<br/>";
        $token = strtok(' ');
    }
?>

I just want to know if I understand this right. Here is what I think about strtok(). To use strtok(), first, you have to set it to a variable($token in this case) with input string ($string in this case) and a separator (' ' in this case). And then you have to use it again in a while loop but this time only specify a separator not the input string because it's already connected to variable $string at the time we first used it. Am I right?

  • 写回答

1条回答 默认 最新

  • dss524049 2014-11-30 07:31
    关注

    Yes, strtok keeps an internal buffer from the first population with $string. It subsequently returns parts of that; whenever you pass it just a new character to split with.

    You can shorten your loop with a do/while construct, btw:

    do {
        echo $token."<br/>";
    }
    while (is_str($token = strtok(' ')));
    

    That's also the drawback of strtok however. Since it works on an globally-internal string buffer, you can only ever use one such loop - it's unsuited to delimit substrings in parallel or work on another buffer alongside.

    Though when you're just splitting with one delimiter, you might as well use PHPs most overused function: explode.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 机器学习简单问题解决
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写