How to use Regular Expressions with preg_split() and implode() Function In PHP
For more complex splitting patterns, you can use regular expressions with the preg_split() function. The implode() function will be used to join array elements into a single string.
- preg_split(“/[\s,]+/”, $string) splits the string $string into an array using a regular expression that matches one or more spaces or commas.
Example: This example shows the use of the above-explained approach.
<?php
// Original string
$string = "Hello and Welcome to w3wiki";
// Splitting the string using regular expression
$splitString = preg_split("/[\s,]+/", $string);
echo "After Splitting\n";
print_r($splitString);
// Joining the array elements
$joinedString = implode("_", $splitString);
echo "\nAfter Joining\n";
echo $joinedString;
?>
Output
After Splitting Array ( [0] => Hello [1] => and [2] => Welcome [3] => to [4] => w3wiki ) After Joining Hello_and_Welcome_to_w3wiki
PHP Program to Split & Join a String
Given a String, the task is to split and join strings in PHP. It is a common operations that allow you to manipulate and manage text data effectively.
Below are the approaches to split and join a string in PHP:
Table of Content
- Using explode() and implode() Function
- Using str_split() and Custom Join Function
- Using Regular Expressions with preg_split() and implode() Function
Contact Us