Php split или explode

Difference Between Split and Explode in PHP

The split() and explode() are two main string function in php. If you are working in php, You must have used these php function in your application. You have also faced some question in interviews regarding difference between php split and explode string function.

In this post, I will let you know what are the differences between Split() and Explode() php function with example.

Simple Usage and example of split() PHP function

The split() function is use to splits the string into an array using a regular expression.The split method returns an array of string data. PHP split() function takes three arguments, first parameter is pattern regular expression which is case sensitive, second is input string and third one is for limit: If the limit is set, the returned array will contain a maximum of limit elements with the last element containing the whole rest of string.

Читайте также:  Grid html css примеры

Warning
This function was DEPRECATED in PHP 5.3.0, and REMOVED in PHP 7.0.0.Alternatives of split function in php7 –

You can read more from Implode And Explode In PHP 7 tutorial.

How to use PHP split Function

split(":", "this:is:a:string"); //returns an array that contains this, is, a, string.

Output :

Array( [0] => this, [1] => is, [2] => a, [3] => string )

Simple Usage and Example of explode() PHP function

The php explode() function splits the string using delimiter and returns an array. PHP explode function takes three argument, first one takes delimiter as a argument, second one is target string and third one is limit : If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string.

Simple Example and Demo of PHP explode function

The below example is used to explode the string using delimiter, The delimiter is this string. Passing first one argument as a delimiter and second one is source string.

explode ("this", "this is a string"); //returns an array that contains array "is a string"

Output

Источник

Cтроку в массив по разделителю в PHP: explode, str_split, strtok — что выбрать?

Для того, чтобы преобразовать строку в массив по разделителю, можно использовать функцию explode()
Необходимые параметры: разделитель и строка.

// Пример 1 $pizza = "кусок1 кусок2 кусок3 кусок4 кусок5 кусок6"; $pieces = explode(" ", $pizza); echo $pieces[0]; // кусок1 echo $pieces[1]; // кусок2 // Пример 2 $data = "foo:*:1023:1000::/home/foo:/bin/sh"; list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data); echo $user; // foo echo $pass; // *

2. preg_split: разбить строку на массив по регулярному выражению

Если возможностей explode() недостаточно, то можно использовать более мощную функцию: preg_split(). Она позволяет разбить строку не по фиксированному набору символов, а по регулярному выражению.

// разбиваем строку по произвольному числу запятых и пробельных символов, // которые включают в себя " ", \r, \t, \n и \f $keywords = preg_split("/[\s,]+/", "hypertext language, programming"); print_r($keywords);
/* Array ( [0] => hypertext [1] => language [2] => programming ) */

Преобразовать строку в массив по количеству символов

Функция str_split() преобразует строку в массив, разбивая ее на элементы с заданным количеством символов. Хотите узнать как ее использовать? Посмотрите документацию.

$str = "Hello Friend"; $arr2 = str_split($str, 3); print_r($arr2)
Array ( [0] => Hel [1] => lo [2] => Fri [3] => end )

Функция strtok(): разбиение строки на токены

Есть еще функция strtok() . Она позволит задать набор из нескольких символов-разделителей, для разделения строки по словам: читать подробнее про strok.

Источник

В чем разница между split () и explode ()?

Но я не могу найти разницу между split() и explode() . join() не устарел, так что дает?

  • explode() значительно быстрее, потому что он не разбивается на основе регулярного выражения, поэтому строка не должна анализироваться парсером regex
  • preg_split() работает быстрее и использует регулярные выражения PCRE для разделения регулярных выражений

join() и implode() являются псевдонимами друг друга и поэтому не имеют различий.

split использует regex, в то время как explode использует фиксированную строку. Если вам нужно regex, используйте preg_split , который использует PCRE (теперь пакет регулярных выражений предпочтительнее в стандартной библиотеке PHP).

В split() вы можете использовать регулярные выражения для разделения строки. В то время как explode() разбивает строку на строку. preg_split – гораздо более быстрая альтернатива, если вам нужны регулярные выражения.

Обе функции используются для разделения строки.

Однако Split используется для разделения строки с использованием регулярного выражения.

С другой стороны, Explode используется для разбиения строки на другую строку.

Например, взорвать («это», «это строка»); вернет « Является ли строка »

Например, Split («+», «This + is string»);

Функция split() разбивает строку на массив с использованием регулярного выражения и возвращает массив.

Функция explode() разделяет строку по строке.

Array ( [0] => I [1] => P [2] => S ) Array ( [0] => I [1] => P [2] => S ) 

Оба используются для разделения строки на массив, но разница в том, что split() использует шаблон для разделения, тогда как explode() использует строку. explode() быстрее, чем split() потому что он не соответствует строке, основанной на регулярном выражении.

Источник

Friendly Fun

Get everything in one place by internet. Get closer and be closer. We are working for your closing achievement. Please be with us and stay with us.

Differences between str_split() and explode() in PHP

Welcome back again. We know both of the function str_split() and explode() in PHP are used to split strings. But here are some differences between them. I will describe shortly about this.

explode() is used to split any string by another string. This means if any string is same that will be missed from the main string and main string will be divided in that point. Here this divider string is as a junction as example.


$str = "This is a text which will be used to do something.";

print_r(explode("t",$str));

?>

$str = "This is a text which will be used to do something.";

print_r(str_split($str));

?>

$str = "This is a text which will be used to do something.";

print_r(explode("t",$str));

?>

$str = "This is a text which will be used to do something.";

print_r(str_split($str));

?>

explode() splits the string in the matching part of the first parameter and delete the matched part,


$str = "This is a text which will be used to do something.";

print_r(explode("text",$str));

?>

But str_split() do not delete anything, just separates the characters.


$str = "This is a text which will be used to do something.";

print_r(str_split($str,5));

?>

str_split() splits the string according to given length. If the length is not given it splits one by one.


$str = "This is a text which will be used to do something.";

print_r(str_split($str));
print_r(str_split($str,5));
print_r(str_split($str,10));

?>

The second parameter of str_split() must be a long or integer number.


$str = "This is a text which will be used to do something.";

print_r(str_split($str,5));
print_r(str_split($str,10));

?>

str_split() is used to split but explode() is used to divide into two based on the matching parts. Again str_split() operates based on the second parameter while explode() operates based on first parameter.

Hope you will find your answers.

Источник

Оцените статью