how to convert a string in array in php i.e
$str="this is string";
should be like this
arr[0]=this arr[1]=is arr[2]=string
The
str_split($str, 3);split the string in 3 character word but i want to convert the string after whitespace in an array.
This question is related to
php
explode() might be the function you are looking for
$array = explode(' ',$str);
Take a look at the explode function.
<?php
// Example 1
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
?>
The explode() function breaks a string into an array.
<?php
$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str));
?>
Output: Array ( [0] => Hello [1] => world. [2] => It's [3] => a [4] => beautiful [5] => day. )
<?php
$str = "Hello Friend";
$arr1 = str_split($str);
$arr2 = str_split($str, 3);
print_r($arr1);
print_r($arr2);
?>
try json_decode like so
<?php
$var = '["SupplierInvoiceReconciliation"]';
$var = json_decode($var, TRUE);
print_r($var);
?>
explode — Split a string by a string
Syntax :
array explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ] )
Example :
// Example 1
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
In your example :
$str = "this is string";
$array = explode(' ', $str);
here, Use explode() function to convert string into array, by a string
click here to know more about explode()
$str = "this is string";
$delimiter = ' '; // use any string / character by which, need to split string into Array
$resultArr = explode($delimiter, $str);
var_dump($resultArr);
Output :
Array
(
[0] => "this",
[1] => "is",
[2] => "string "
)
it is same as the requirements:
arr[0]="this";
arr[1]="is";
arr[2]="string";
With explode function of php
$array=explode(" ",$str);
This is a quick example for you http://codepad.org/Pbg4n76i
There is a function in PHP specifically designed for that purpose, str_word_count()
. By default it does not take into account the numbers and multibyte characters, but they can be added as a list of additional characters in the charlist
parameter. Charlist parameter also accepts a range of characters as in the example.
One benefit of this function over explode()
is that the punctuation marks, spaces and new lines are avoided.
$str = "1st example:
Alte Füchse gehen schwer in die Falle. ";
print_r( str_word_count( $str, 1, '1..9ü' ) );
/* output:
Array
(
[0] => 1st
[1] => example
[2] => Alte
[3] => Füchse
[4] => gehen
[5] => schwer
[6] => in
[7] => die
[8] => Falle
)
*/
You can achieve this even without using explode and implode function. Here is the example:
Input:
This is my world
Code:
$part1 = "This is my world";
$part2 = str_word_count($part1, 1);
Output:
Array( [0] => 'This', [1] => 'is', [2] => 'my', [3] => 'world');
Source: Stackoverflow.com