UNPKG

phpjs

Version:

php.js offers community built php functions in javascript

81 lines (71 loc) 2.62 kB
--- layout: page title: "JavaScript strtok function" comments: true sharing: true footer: true alias: - /functions/view/strtok:552 - /functions/view/strtok - /functions/view/552 - /functions/strtok:552 - /functions/552 --- <!-- Generated by Rakefile:build --> A JavaScript equivalent of PHP's strtok {% codeblock strings/strtok.js lang:js https://raw.github.com/kvz/phpjs/master/functions/strings/strtok.js raw on github %} function strtok (str, tokens) { // From: http://phpjs.org/functions // + original by: Brett Zamir (http://brett-zamir.me) // % note 1: Use tab and newline as tokenizing characters as well // * example 1: $string = "\t\t\t\nThis is\tan example\nstring\n"; // * example 1: $tok = strtok($string, " \n\t"); // * example 1: $b = ''; // * example 1: while ($tok !== false) {$b += "Word="+$tok+"\n"; $tok = strtok(" \n\t");} // * example 1: $b // * returns 1: "Word=This\nWord=is\nWord=an\nWord=example\nWord=string\n" // BEGIN REDUNDANT this.php_js = this.php_js || {}; // END REDUNDANT if (tokens === undefined) { tokens = str; str = this.php_js.strtokleftOver; } if (str.length === 0) { return false; } if (tokens.indexOf(str.charAt(0)) !== -1) { return this.strtok(str.substr(1), tokens); } for (var i = 0; i < str.length; i++) { if (tokens.indexOf(str.charAt(i)) !== -1) { break; } } this.php_js.strtokleftOver = str.substr(i + 1); return str.substring(0, i); } {% endcodeblock %} - [Raw function on GitHub](https://github.com/kvz/phpjs/blob/master/functions/strings/strtok.js) Please note that php.js uses JavaScript objects as substitutes for PHP arrays, they are the closest match to this hashtable-like data structure. Please also note that php.js offers community built functions and goes by the [McDonald's Theory](https://medium.com/what-i-learned-building/9216e1c9da7d). We'll put online functions that are far from perfect, in the hopes to spark better contributions. Do you have one? Then please just: - [Edit on GitHub](https://github.com/kvz/phpjs/edit/master/functions/strings/strtok.js) ### Example 1 This code {% codeblock lang:js example %} $string = "\t\t\t\nThis is\tan example\nstring\n"; $tok = strtok($string, " \n\t"); $b = ''; while ($tok !== false) {$b += "Word="+$tok+"\n"; $tok = strtok(" \n\t");} $b {% endcodeblock %} Should return {% codeblock lang:js returns %} "Word=This\nWord=is\nWord=an\nWord=example\nWord=string\n" {% endcodeblock %} ### Other PHP functions in the strings extension {% render_partial _includes/custom/strings.html %}