Understanding PHP explode() Function: Syntax, Examples, and Use Cases
This article explains PHP's explode() function, detailing its syntax, parameters, and optional limit, and provides multiple code examples demonstrating string-to-array splitting with various delimiters and extracting URL components, helping developers effectively manipulate strings in backend applications.
PHP is a widely used server-side scripting language with powerful string handling capabilities; this article focuses on its built-in explode() function.
The explode() function splits a string into an array based on a delimiter, accepting three parameters: the delimiter, the input string, and an optional limit (default PHP_INT_MAX ).
Basic syntax:
<code>array explode(string $delimiter, string $string, int $limit = PHP_INT_MAX)</code>Example 1 – splitting a comma-separated string:
<code><?php
$str = "Hello,World,PHP";
$arr = explode(",", $str);
print_r($arr);
?></code>Output:
<code>Array
(
[0] => Hello
[1] => World
[2] => PHP
)</code>Example 2 – using a multi-character delimiter (vertical bar):
<code><?php
$str = "Hello|World|PHP";
$arr = explode("|", $str);
print_r($arr);
?></code>Result is the same three-element array.
Example 3 – extracting a domain name from a URL by splitting on the dot character:
<code><?php
$url = "https://www.example.com";
$arr = explode(".", $url);
$domain = $arr[1];
echo $domain;
?></code>Output:
<code>www</code>In summary, explode() is a versatile function for converting strings to arrays or retrieving specific parts of a string, making it essential for backend PHP development.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.