How To Split a String into Pieces?

deepak singh
Posts: 686
Joined: Fri Sep 30, 2016 4:19 pm

How To Split a String into Pieces?

Postby deepak singh » Sat Oct 01, 2016 4:51 pm

How To Split a String into Pieces?

rameshkhd
Posts: 1279
Joined: Sun Aug 28, 2016 10:45 am

Re: How To Split a String into Pieces?

Postby rameshkhd » Sat Oct 01, 2016 4:56 pm

There are two functions you can use to split a string into pieces:
• explode(substring, string) - Splitting a string based on a substring. Faster than split().
• split(pattern, string) - Splitting a string based on a regular expression pattern. Better than explode() in handling complex cases.
Both functions will use the given criteria, substring or pattern, to find the splitting points in the string, break the string into pieces at the splitting points, and return the pieces in an array. Here is a PHP script on how to use explode() and split():
<?php
$list = explode("_","php_strting_function.html");
print("explode() returns:\n");
print_r($list);
$list = split("[_.]","php_strting_function.html");
print("split() returns:\n");
print_r($list);
?>
This script will print:
explode() returns:
Array
(
[0] => php
[1] => strting
[2] => function.html
)
split() returns:
Array
(
[0] => php
[1] => strting
[2] => function
[3] => html
)
The output shows you the power of power of split() with a regular expression pattern as the splitting criteria. Pattern "[_.]" tells split() to split whenever there is a "_" or ".".


Return to “PHP”

Who is online

Users browsing this forum: No registered users and 2 guests