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 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流