More String Functions
Explode, implode, reverse and repeat strings with handy built-in functions.
Syntax
explode($separator, $string);PHP ships with hundreds of string helpers. A few more you will use often:
explode()— split a string into an array.implode()— join an array into a string.strrev()— reverse a string.str_repeat()— repeat a string.sprintf()— format a string.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Split a CSV row into an array with explode() to process each column separately.
- Join an array of tags back into a comma-separated string for display with implode().
- Reverse a string with strrev() to implement a palindrome check in a coding exercise.
More examples
explode and implode
explode() splits a string into an array; implode() joins it back with a chosen separator.
<?php
$csv = 'apple,banana,cherry';
$tags = explode(',', $csv); // ['apple','banana','cherry']
$tags[] = 'date';
$result = implode(' | ', $tags); // apple | banana | cherry | date
echo $result;str_repeat and strrev
str_repeat() builds repeated-character strings; strrev() reverses a string for palindrome or mirror operations.
<?php
$divider = str_repeat('-', 40);
$word = 'racecar';
$isPalin = $word === strrev($word);
echo $divider . "\n";
echo $isPalin ? "$word is a palindrome" : "Not a palindrome";substr and chunk_split
substr() extracts a portion of a string; chunk_split() breaks it into fixed-size chunks with a delimiter.
<?php
$text = 'The quick brown fox jumps over the lazy dog';
$excerpt = substr($text, 0, 20) . '...';
echo $excerpt; // The quick brown fox...
$key = 'ABCDEFGHIJ';
$pretty = chunk_split($key, 5, '-');
echo $pretty; // ABCDE-FGHIJ-
Discussion