PHP Modules Tutorials - Herong's Tutorial Examples - v5.18, by Herong Yang
preg_split() - Split String into Tokens
This section provides a tutorial example on how to split a string with pattern delimiters using the preg_split() function.
If you want to split a string into tokens with delimiter pattern, you can use the preg_split() function:
$tokens = preg_split($pattern, $subject); where: $pattern: Regular express pattern as the delimiter $subject: String to be split $tokens: Subjects that are affected by replacements
Here is an example script that splits a URL into multiple parts:
<?php
# preg-split-string.php
# Copyright 2009-2024 (c) HerongYang.com. All Rights Reserved.
$subject = "https://herongyang.com/PHP/index.html";
$pattern = "/(:\/\/)|\//";
$tokens = preg_split($pattern, $subject);
print("Split subject into tokens:\n");
print(" Subject: $subject\n");
print(" Pattern: $pattern\n");
print(" Tokens:\n".json_encode($tokens, JSON_PRETTY_PRINT)."\n");
?>
If you run the above script, you will see the following output:
herong$ php preg-split-string.php
Subject: https://herongyang.com/PHP/index.html
Pattern: /(:\/\/)|\//
Tokens:
[
"https",
"herongyang.com",
"PHP",
"index.html"
]
Table of Contents
Introduction and Installation of PHP
Managing PHP Engine and Modules on macOS
Managing PHP Engine and Modules on CentOS
DOM Module - Parsing HTML Documents
GD Module - Manipulating Images and Pictures
MySQLi Module - Accessing MySQL Server
OpenSSL Module - Cryptography and SSL/TLS Toolkit
►PCRE Module - Perl Compatible Regular Expressions
preg_match() - Regular Expression Match
preg_grep() - Search Array Members
preg_replace() - Replace Matched Substring
►preg_split() - Split String into Tokens
preg_quote() - Escape Characters in Pattern
SOAP Module - Creating and Calling Web Services
SOAP Module - Server Functions and Examples