Support PHP Version: PHP 7.1, PHP 7.2, PHP 7.3, PHP 7.4, PHP 8.0, PHP 8.1, PHP 8.2, PHP 8.3 With Latest All Version Support.
In PHP, there isn’t a built-in function named `strtok()` in the standard library as you might find in other languages like C. However, PHP does have a similar function called `explode()` or `preg_split()` which can achieve similar functionality.
Here’s how you can use `explode()` to split a string into an array based on a delimiter:
<?php $string = "Hello, World! This is a sample string."; $delimiter = " "; // space character $words = explode($delimiter, $string); foreach ($words as $word) { echo $word . "\n"; } ?>
Output:
Hello, World! This is a sample string.
In this example, the `explode()` function splits the string `$string` into an array of words using the space character as the delimiter. Then, we iterate through the resulting array and print each word.
Alternatively, if you need more complex pattern-based splitting, you can use `preg_split()` which splits a string by a regular expression pattern. Here’s an example:
<?php $string = "Hello, World! This is a sample string."; $words = preg_split("/[\s,]+/", $string); foreach ($words as $word) { echo $word . "\n"; } ?>
Output:
Hello World! This is a sample string.
In this example, the regular expression `”/[\s,]+/”` matches one or more whitespace characters or commas, effectively splitting the string into words while handling variations in whitespace or punctuation. Then, we iterate through the resulting array and print each word.