- explode
- Parameters
- Return Values
- Changelog
- Examples
- Notes
- See Also
- User Contributed Notes 3 notes
- str_split
- Errors/Exceptions
- Changelog
- Examples
- Notes
- See Also
- User Contributed Notes 3 notes
- Split passed string array with space in php
- Split the strings with space and comma and print this in a new line in php
- Split text using multiple delimiters into an array of trimmed values
- Regular Expression to split on spaces unless in quotes
- PHP: Split a string by comma(,) but ignoring anything inside square brackets?
explode
Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string separator .
Parameters
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 .
If the limit parameter is negative, all components except the last — limit are returned.
If the limit parameter is zero, then this is treated as 1.
Note:
Prior to PHP 8.0, implode() accepted its parameters in either order. explode() has never supported this: you must ensure that the separator argument comes before the string argument.
Return Values
Returns an array of string s created by splitting the string parameter on boundaries formed by the separator .
If separator is an empty string («»), explode() throws a ValueError . If separator contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned. If separator values appear at the start or end of string , said values will be added as an empty array value either in the first or last position of the returned array respectively.
Changelog
Version | Description |
---|---|
8.0.0 | explode() will now throw ValueError when separator parameter is given an empty string ( «» ). Previously, explode() returned false instead. |
Examples
Example #1 explode() examples
// Example 1
$pizza = «piece1 piece2 piece3 piece4 piece5 piece6» ;
$pieces = explode ( » » , $pizza );
echo $pieces [ 0 ]; // piece1
echo $pieces [ 1 ]; // piece2
?php
// Example 2
$data = «foo:*:1023:1000::/home/foo:/bin/sh» ;
list( $user , $pass , $uid , $gid , $gecos , $home , $shell ) = explode ( «:» , $data );
echo $user ; // foo
echo $pass ; // *
Example #2 explode() return examples
/*
A string that doesn’t contain the delimiter will simply
return a one-length array of the original string.
*/
$input1 = «hello» ;
$input2 = «hello,there» ;
$input3 = ‘,’ ;
var_dump ( explode ( ‘,’ , $input1 ) );
var_dump ( explode ( ‘,’ , $input2 ) );
var_dump ( explode ( ‘,’ , $input3 ) );
?php
The above example will output:
array(1) ( [0] => string(5) "hello" ) array(2) ( [0] => string(5) "hello" [1] => string(5) "there" ) array(2) ( [0] => string(0) "" [1] => string(0) "" )
Example #3 limit parameter examples
// positive limit
print_r ( explode ( ‘|’ , $str , 2 ));
// negative limit
print_r ( explode ( ‘|’ , $str , — 1 ));
?>
The above example will output:
Array ( [0] => one [1] => two|three|four ) Array ( [0] => one [1] => two [2] => three )
Notes
Note: This function is binary-safe.
See Also
- preg_split() — Split string by a regular expression
- str_split() — Convert a string to an array
- mb_split() — Split multibyte string using regular expression
- str_word_count() — Return information about words used in a string
- strtok() — Tokenize string
- implode() — Join array elements with a string
User Contributed Notes 3 notes
Note that an empty input string will still result in one element in the output array. This is something to remember when you are processing unknown input.
For example, maybe you are splitting part of a URI by forward slashes (like «articles/42/show» => [«articles», «42», «show»]). And maybe you expect that an empty URI will result in an empty array («» => []). Instead, it will contain one element, with an empty string:
$uri = » ;
$parts = explode ( ‘/’ , $uri );
var_dump ( $parts );
Be careful, while most non-alphanumeric data types as input strings return an array with an empty string when used with a valid separator, true returns an array with the string «1»!
var_dump(explode(‘,’, null)); //array(1) < [0]=>string(0) «» >
var_dump(explode(‘,’, false)); //array(1) < [0]=>string(0) «» >
var_dump(explode(‘,’, true)); //array(1) < [0]=>string(1) «1» >
If you want to directly take a specific value without having to store it in another variable, you can implement the following:
echo $status_only = explode(‘-‘, $status)[0];
str_split
If the optional length parameter is specified, the returned array will be broken down into chunks with each being length in length, except the final chunk which may be shorter if the string does not divide evenly. The default length is 1 , meaning every chunk will be one byte in size.
Errors/Exceptions
If length is less than 1 , a ValueError will be thrown.
Changelog
Version | Description |
---|---|
8.2.0 | If string is empty an empty array is now returned. Previously an array containing a single empty string was returned. |
8.0.0 | If length is less than 1 , a ValueError will be thrown now; previously, an error of level E_WARNING has been raised instead, and the function returned false . |
Examples
Example #1 Example uses of str_split()
$arr1 = str_split ( $str );
$arr2 = str_split ( $str , 3 );
print_r ( $arr1 );
print_r ( $arr2 );
The above example will output:
Array ( [0] => H [1] => e [2] => l [3] => l [4] => o [5] => [6] => F [7] => r [8] => i [9] => e [10] => n [11] => d ) Array ( [0] => Hel [1] => lo [2] => Fri [3] => end )
Notes
Note:
str_split() will split into bytes, rather than characters when dealing with a multi-byte encoded string. Use mb_str_split() to split the string into code points.
See Also
- mb_str_split() — Given a multibyte string, return an array of its characters
- chunk_split() — Split a string into smaller chunks
- preg_split() — Split string by a regular expression
- explode() — Split a string by a string
- count_chars() — Return information about characters used in a string
- str_word_count() — Return information about words used in a string
- for
User Contributed Notes 3 notes
The function str_split() is not ‘aware’ of words. Here is an adaptation of str_split() that is ‘word-aware’.
$array = str_split_word_aware (
‘In the beginning God created the heaven and the earth. And the earth was without form, and void; and darkness was upon the face of the deep.’ ,
32
);
/**
* This function is similar to str_split() but this function keeps words intact; it never splits through a word.
*
* @return array
*/
function str_split_word_aware ( string $string , int $maxLengthOfLine ): array
if ( $maxLengthOfLine <= 0 ) throw new RuntimeException ( sprintf ( 'The function %s() must have a max length of line at least greater than one' , __FUNCTION__ ));
>
$lines = [];
$words = explode ( ‘ ‘ , $string );
$currentLine = » ;
$lineAccumulator = » ;
foreach ( $words as $currentWord )
$currentWordWithSpace = sprintf ( ‘%s ‘ , $currentWord );
$lineAccumulator .= $currentWordWithSpace ;
if ( strlen ( $lineAccumulator ) < $maxLengthOfLine ) $currentLine = $lineAccumulator ;
continue;
>
// Overwrite the current line and accumulator with the current word
$currentLine = $currentWordWithSpace ;
$lineAccumulator = $currentWordWithSpace ;
>
if ( $currentLine !== » ) $lines [] = $currentLine ;
>
array( 5 ) [ 0 ]=> string ( 29 ) «In the beginning God created »
[ 1 ]=> string ( 30 ) «the heaven and the earth. And »
[ 2 ]=> string ( 28 ) «the earth was without form, »
[ 3 ]=> string ( 27 ) «and void; and darkness was »
[ 4 ]=> string ( 27 ) «upon the face of the deep. »
>
Split passed string array with space in php
Solution 3: use this function for string length and use explode to split after space and comma.. explode syntax: Solution 1: Use a regular expression and preg_split. This solution should work if your strings inside brackets are valid PHP arrays/JSON string
Split the strings with space and comma and print this in a new line in php
And why would you use regex for that? To make it unnecessary complicated?
$address="Palvelicham,Mananthavady Kodanad"; $replaced = str_replace(" ", "\n", $address);
Palvelicham,Mananthavady Kodanad
Try this. Haven’t tested, but should work.
$str = 'Palvelicham,Mananthavady Kodanad'; $formated_str = implode('\r\n', explode(' ', $str));
use this function for string length and use explode to split after space and comma..
function limit_text($text, $length) // Limit Text < if(strlen($text) >$length) < $stringCut = substr($text, 0, $length); $text = substr($stringCut, 0, strrpos($stringCut, ' ')); >return $text; >
How can we split a string by sentence as a delimiter in Java?, The split() method of the String class accepts a String value representing the delimiter and splits into an array of tokens (words),
Split text using multiple delimiters into an array of trimmed values
Use a regular expression and preg_split.
In the case you mention, you would get the split array with:
$splitString = preg_split('/(\/|\,| with |\&/)/', $string);
To concisely write the pattern use a character class for the single-character delimiters and add the with delimiter as a value after the pipe (the «or» character in regex). Allow zero or more spaces on either side of the group of delimiters so that the values in the output don’t need to be trimmed.
I am using the PREG_SPLIT_NO_EMPTY function flag in case a delimiter occurs at the start or end of the string and you don’t want to have any empty elements generated.
$string = 'first past/ going beyond & then turn with everyone'; var_export( preg_split('~ ?([/,&]|with) ?~', $string, 0, PREG_SPLIT_NO_EMPTY) );
array ( 0 => 'first past', 1 => 'going beyond', 2 => 'then turn', 3 => 'everyone', )
How to split a string by multiple delimiters in PHP?, 4 Answers 4 ; 49 · ‘, print_r( preg_split( $pattern, $string ), 1 ),?php>
Regular Expression to split on spaces unless in quotes
Regex regex = new Regex(@"\w+|""[\w\s]*""");
Or if you need to exclude » characters:
Regex .Matches(input, @"(?\w+)|\""(?[\w\s]*)""") .Cast() .Select(m => m.Groups["match"].Value) .ToList() .ForEach(s => Console.WriteLine(s));
Lieven’s solution gets most of the way there, and as he states in his comments it’s just a matter of changing the ending to Bartek’s solution. The end result is the following working regEx:
Input: Here is «my string» it has «six matches»
Unfortunately it’s including the quotes. If you instead use the following:
And explicitly capture the «token» matches as follows:
RegexOptions options = RegexOptions.None; Regex regex = new Regex( @"((""((?.*?)(?
Token[0]: 'Here' Token[1]: 'is' Token[2]: 'my string' Token[3]: 'it' Token[4]: 'has' Token[5]: ' six matches'
The top answer doesn’t quite work for me. I was trying to split this sort of string by spaces, but it looks like it splits on the dots (‘.’) as well.
"the lib.lib" "another lib".lib
I know the question asks about regexs, but I ended up writing a non-regex function to do this:
/// /// Splits the string passed in by the delimiters passed in. /// Quoted sections are not split, and all tokens have whitespace /// trimmed from the start and end. public static List split(string stringToSplit, params char[] delimiters) < Listresults = new List(); bool inQuote = false; StringBuilder currentToken = new StringBuilder(); for (int index = 0; index < stringToSplit.Length; ++index) < char currentCharacter = stringToSplit[index]; if (currentCharacter == '"') < // When we see a ", we need to decide whether we are // at the start or send of a quoted section. inQuote = !inQuote; >else if (delimiters.Contains(currentCharacter) && inQuote == false) < // We've come to the end of a token, so we find the token, // trim it and add it to the collection of results. string result = currentToken.ToString().Trim(); if (result != "") results.Add(result); // We start a new token. currentToken = new StringBuilder(); >else < // We've got a 'normal' character, so we add it to // the curent token. currentToken.Append(currentCharacter); >> // We've come to the end of the string, so we add the last token. string lastResult = currentToken.ToString().Trim(); if (lastResult != "") results.Add(lastResult); return results; >
Split string into line array php Code Example, “split string into line array php” Code Answer · php split string · Browse PHP Answers by Framework.
PHP: Split a string by comma(,) but ignoring anything inside square brackets?
yeah, regex — select all commas, ignore in square brakets
For your example data you might use preg_split and use a regex to match a comma or match the part with the square brackets and then skip that using (*SKIP)(*FAIL).
$pattern = '/,|\[[^]]+\](*SKIP)(*FAIL)/'; $string = "'==', ['abc', 'xyz'], 1"; $result = preg_split($pattern, $string); print_r($result);
Array ( [0] => '==' [1] => ['abc', 'xyz'] [2] => 1 )
For your example, if you don’t want to use regex and want to stick with the explode() function you are already using, you could simply replace all instances of ‘, ‘ with ‘,’ , then break the string in parts by , (followed by a space) instead of just the comma.
This makes it so things inside the brackets don’t have the explode delimiter, thus making them not break apart into the array.
This has an additional problem, if you had a string like ‘==’, ‘test-taco’ , this solution would not work. This problem, along with many other problems probably, can be solved by removing the single quotes from the separate strings, as ==, test-taco would still work.
This solution should work if your strings inside brackets are valid PHP arrays/JSON string
$str = "'==', ['abc', 'xyz'], 1"; $str = str_replace("', '", "','", $str); $str = explode(", ", $str);
Though I recommend regex as it may solve some underlying issues that I don’t see.
Array ( [0] => '==' [1] => ['abc','xyz'] [2] => 1 )
PHP split string into array at position Code Example, php split string · php slice string by character · php divide string into parts ; php split string at first space · split functions.php · php split string by