php split string by delimiter
PHP метод explode для разбиения строки с тремя примерами
Метод PHP explode используется для разбиения строки на заданное число подстрок.
Синтаксис метода
Пример использования PHP метода explode :
Пример использования explode для разбиения номера телефона
В этом примере мы объявили строковую переменную и присвоили ей номер телефона следующего формата:
После этого применили метод explode для разбиения строки с помощью дефиса ( тире ) в качестве разделителя. Возвращенный массив строк присвоили массиву.
Затем использовали цикл fогеасh для отображения значений элементов массива, которые являются подстроками номера телефона. Поскольку параметр limit не указан, весь номер телефона будет разбит на три подстроки:
Посмотреть демо и код
Пример с пробелом в качестве разделителя
В этом примере PHP explode переноса строки использован пробел в качестве разделителя. Для примера возьмем это строку:
This is explode tutorial that enables string split in PHP.
Наконец, применили функцию count() для вывода количества подстрок в массиве:
Посмотреть демо и код
Пример с параметром limit
Это пример, описанный выше, за исключением того, что здесь мы использовали параметр limit для указания количества разбиений в строке. Ниже показана строка, которая была использована:
This is explode tutorial that enables string split in PHP.
В PHP explode примере, когда мы использовали пробел в качестве разделителя, было возвращено всего 10 подстрок. На этот раз с помощью параметра limit было определено 5 разбиений:
Посмотреть демо и код
Для чего нужен метод explode
Метод explode ( PHP split ) используется для разбиения заданной строки. Допустим, что веб-форма принимает телефонный номер с кодом страны и области в следующем формате:
Нам нужно отделить код страны и области, которые разделены дефисом. Для разбиения телефонного номера можно воспользоваться explode с разделителем дефисом ( тире ) после принятия номера в качестве входного параметра.
Поскольку explode возвращает массив подстрок, метод explode разобьет номер в следующий массив элементов:
Как использовать функцию PHP explode
В функции PHP explode можно указать три параметра. Последний из них — необязательный, так как указывать количество разбиений ( максимальное количество подстрок ) необязательно.
Описание каждого параметра:
Если в explode array PHP аргумент limit является положительным, возвращаемый массив будет содержать максимальное количество элементов, при этом последний элемент будет содержать остаток строки.
Также можно использовать отрицательное значение. В этом случае все подстроки ( кроме последней ) будут возвращены.
Поскольку explode возвращает массив подстрок, то можно присвоить его массиву. После применения метода можно использовать цикл fогеаch, чтобы перебрать массив элементов, как показано в приведенных выше примерах.
Примечание: Также можно использовать метод str_split для преобразования строки в массив.
Пожалуйста, оставляйте свои мнения по текущей теме статьи. Мы крайне благодарны вам за ваши комментарии, подписки, отклики, дизлайки, лайки!
php explode: split string into words by using space a delimiter
Works fine, but spaces still go into array:
I would prefer to have words only with no spaces and keep the information about the number of spaces separate.
Just added: (1, 1, 4) means one space after the first word, one space after the second word and 4 spaces after the third word.
Is there any way to do it fast?
7 Answers 7
For splitting the String into an array, you should use preg_split:
Your second part (counting spaces):
Here is one way, splitting the string and running a regex once, then parsing the results to see which segments were captured as the split (and therefore only whitespace), or which ones are words:
You can use preg_split() for the first array:
Another way to do it would be using foreach loop.
Here are the results of performance tests:
int(1378392870) Array ( [0] => This [1] => is [2] => a [3] => string ) Array ( [0] => 1 [1] => 1 [2] => 4 ) int(1378392871) Array ( [0] => This [1] => is [2] => a [3] => string ) Array ( [0] => 1 [1] => 1 [2] => 4 ) int(1378392873)
Splitting with regex has been demonstrated well by earlier answers, but I think this is a perfect case for calling ctype_space() to determine which result array should receive the encountered value.
Splitting strings in PHP and get last part
I need to split a string in PHP by «-» and get the last part.
This is the code I’ve come up with:
which works fine, except:
If my input-string does not contain any «-«, I must get the whole string, like from:
I need to get back
and it needs to be as fast as possible. Any help is appreciated!
13 Answers 13
split($pattern,$string) split strings within a given pattern or regex (it’s deprecated since 5.3.0)
preg_split($pattern,$string) split strings within a given regex pattern
explode($pattern,$string) split strings within a given pattern
end($arr) get last array element
$strArray = explode(‘-‘,$str)
$lastElement = end($strArray)
And there’s a hardcore way to do this:
EDIT::Finally got around to removing the E_STRICT issue
Just check whether or not the delimiting character exists, and either split or don’t:
This code will do that
As has been mentioned by others, if you don’t assign the result of explode() to a variable, you get the message:
E_STRICT: Strict standards: Only variables should be passed by reference
The correct way is:
which won’t cause E_STRICT warning in PHP 5 (PHP magic). Although the warning will be issued in PHP 7, so adding @ in front of it can be used as a workaround.
To satisfy the requirement that «it needs to be as fast as possible» I ran a benchmark against some possible solutions. Each solution had to satisfy this set of test cases.
Here are the solutions:
Here are the results after each solution was run against the test cases 1,000,000 times:
PHP Split String
By Shree Ram Sharma
Introduction to PHP Split String
The split string is one of the basic operations for any programming language. There are various built-in functions in PHP to deal with split relation operations. When we come to know the word split, we will experience the breaking of a single string into the multiple strings. There are various ways we can split a string as per our business requirements. In other words, if you want to split a string to get the string character by character (1 character each), by space, by special character etc. We can also go with the size combination while dealing with the string split.
Syntax:
Web development, programming languages, Software testing & others
explode(Separator, String, Limit)
The limit is an optional parameter.
preg_split(RegularExpressionPattern, String, Limit, Flags)
RegularExpressionPattern- required parameter.
Working of PHP Split String
Before moving ahead with the string split, we must have a string first to perform the operation on that string. After string, we can come to the required delimiter upon which the string split operation needs to perform.
1. User of explode() Function
This function can be used to break a string into an array of string.
Let’s understand the same with a basic example:
2. The User of preg_split()
The above of the code will break the string either by – or by the white space.
3. The user of str_split
This can also do the same job, converting a string to an array of smaller strings.
$string = «Welcome to the India»; // a string
$outputArr = str_split(«Welcome to the India»);
Examples to Implement PHP Split String
Below are the Example of PHP Split String:
Example #1
Split a string where we find the white space.
Code:
Output:
Example #2
In this example, we will see how a string can be split into multiple strings using a regular expression.
Code:
Output:
Example #3
Let’s see another very simple example of string split using the str_split() function.
Code:
«;
echo «Array of string after string str_split:\n»;
$arrays = str_split($string);
print_r($arrays);
?>
Output:
Example #4
String split using str_split() function with a specified length.
Code:
Output:
Explanation: Looking at the output of the above program, we can say that some string of length 2 or 3 but we have mentioned the length as a 4. This is just because the string element with 2 carries 2 spaces and the string with 3 characters carry one space with it.
Example #5
Now, using the string split method lets try to get the first string from of that string.
Code:
Output:
Conclusion
We can simply say, in PHP there are various ways to handle the string split. Built-in PHP functions can be used as per the business requirements to process the split string. But code or developer should be aware of using these and the pros and cons of it. Most of the functions of the string split changed the string into an array then we can get the specified string from that array.
Recommended Article
This is a guide to the PHP Split String. Here we discuss the Introduction of PHP Split String and its Examples and Code Implementation. You can also go through our other suggested articles to learn more –
str_split
str_split — Преобразует строку в массив
Описание
Преобразует строку в массив.
Список параметров
Максимальная длина фрагмента.
Возвращаемые значения
Примеры
Пример #1 Пример использования str_split()
Результат выполнения данного примера:
Примечания
Функция str_split() производит разбивку по байтам, а не по символам, в случае использования строк в многобайтных кодировках.
Смотрите также
User Contributed Notes 40 notes
A proper unicode string split;
print_r(str_split($s, 3));
print_r(str_split_unicode($s, 3));
A new version of «str_split_unicode» prev.
heres my version for php4 and below
The manual don’t says what is returned when you parse a different type of variable.
This is the example:
= «Long» ; // More than 1 char
$str2 = «x» ; // Only 1 char
$str3 = «» ; // Empty String
$str4 = 34 ; // Integer
$str5 = 3.4 ; // Float
$str6 = true ; // Bool
$str7 = null ; // Null
I noticed in the post below me that his function would return an array with an empty key at the end.
So here is just a little fix for it.
I needed a function that could split a string from the end with any left over chunk being at the beginning of the array (the beginning of the string).
The documentation fails to mention what happens when the string length does not divide evenly with the chunk size. Not sure if the same behavior for all versions of PHP so I offer the following code to determine this for your installation. On mine [version 5.2.17], the last chunk is an array the length of the remaining chars.
The very handy str_split() was introduced in PHP 5, but a lot of us are still forced to use PHP 4 at our host servers. And I am sure a lot of beginners have looked or are looking for a function to accomplish what str_split() does.
Taking advantge of the fact that strings are ‘arrays’ I wrote this tiny but useful e-mail cloaker in PHP, which guarantees functionality even if JavaScript is disabled in the client’s browser. Watch how I make up for the lack of str_split() in PHP 4.3.10.
// The result is an email address in HTML entities which, I hope most email address harvesters can’t read.
>
print cloakEmail ( ‘someone@nokikon.com’ );
?>
###### THE CODE ABOVE WITHOUT COMMENTS ######
It’s mentioned in the Return Values section above («If the split_length length exceeds the length of string, the entire string is returned as the first (and only) array element»), but note that an input of empty string will return array(1) < [0]=>string(0) «» >. Interestingly an input of NULL will also return array(1) < [0]=>string(0) «» >.
revised function from tatsudoshi
The previous suggestion is almost correct (and will only working for strlen=1. The working PHP4 function is:
Even shorter version:
//place each character (or group of) of the
string into and array
the fastast way (that fits my needs) to replace str_split() in php 4 i found is this: