Doubt regarding Strtok in PHP

橙三吉。 提交于 2019-12-13 20:24:01

问题


<?php
    $string = "sandesh commented on institue international institute of technology";
    /* Use tab and newline as tokenizing characters as well  */
    $tok = strtok($string, " \n\t");
    echo $tok
    ?>

The above code gives me output sandesh.

But if I want the output "commented on institute international institute of technology", then how should I modify the above code.

Thanks and Regards Sandesh


回答1:


<?php
$string = "sandesh commented on institue international institute of technology";
echo substr($string,strpos($string," ")+1);

documentation

  • http://php.net/manual/en/function.strpos.php
  • http://php.net/manual/en/function.substr.php

Edit

i actually need the string after the fourth token

<?php
$string = "sandesh commented on institue international institute of technology";
$str_array = explode(" ",$string);
$str_array = slice($str_array,4);
echo implode(" ",$str_array);
  • http://php.net/manual/en/function.explode.php
  • http://www.php.net/manual/en/function.implode.php
  • http://php.net/manual/en/function.array-slice.php



回答2:


Because you're tokenizing based on space, strtok gives you the first word. The next time you call strtok, you'll get the second word, etc. There is no way, given the string that you have and the token that you supply, to get the rest of the string as a single token.




回答3:


is there any way directly i can get the string after fourth token , without putting into loop.

This will get the string after the fourth space in one pass.

<?php
$string = "sandesh commented on institue international institute of technology";
preg_match('/(?:.*?\s){4}(.*)/', $string, $m);
$new_string = $m[1];
echo $new_string;
?>

Output

international institute of technology



来源:https://stackoverflow.com/questions/7362547/doubt-regarding-strtok-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!