This question already has answers here:
Creating an array from a string separated by spaces
(7 answers)
Closed 1 year ago.
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); splits the string in 3 character word but I need to convert the string after whitespace in an array.
Use explode function
$array = explode(' ', $string);
The first argument is delimiter
With explode function of php
$array=explode(" ",$str);
This is a quick example for you http://codepad.org/Pbg4n76i
<?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);
?>
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
?>
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
)
*/
explode() might be the function you are looking for
$array = explode(' ',$str);
explode — Split a string by a string
Syntax :
array explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ] )
$delimiter : based on which you want to split string
$string. : The string you want to split
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);
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');
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";
Related
How to convert this string
*|text:student:required|*
( * and | is part of string ) into array like this
['text' ,'student','required']
try the following:
$str = '*|text:student:required|*';
$str = preg_replace("/[|*]/", '', $str);
$arr = explode(':', $str);
this simply removes the | AND * from the string using preg_replace() and the turns the string into an array using explode
Here you go:
$str = "|text:student:required|";
$str = trim($str,"|");
$str = trim($str,"*");
$x = explode(':',$str);
print_r($x);die;
The shortest one with preg_split function:
$s = '*|text:student:required|* ';
$result = preg_split('/[*:| ]+/', $s, -1, PREG_SPLIT_NO_EMPTY);
print_r($result);
The output:
Array
(
[0] => text
[1] => student
[2] => required
)
$string = "*|text:student:required|";
$string = str_replace("*", "", str_replace("|","", $string));
$array = explode(':', $string);
I have a string like this:
$string = 'Apple, Orange, Lemone';
I want to make this string to:
$array = array('apple'=>'Apple', 'orang'=>'Orange', 'lemone'=>'Lemone');
How to achieve this?
I used the explode function like this:
$string = explode(',', $string );
But that only gives me this:
Array ( [0] => Apple [1] => Orange [2] => Lemone )
Somebody says this question is a duplicate of this SO question: Split a comma-delimited string into an array?
But that question is not addressing my problem. I have already reached the answer of that question, please read my question. I need to change that result array's key value and case. see:
Array
(
[0] => 9
[1] => admin#example.com
[2] => 8
)
to like this
Array
(
[9] => 9
[admin#example.com] => admin#example.com
[8] => 8
)
You may try :
$string = 'Apple, Orange, Lemone';
$string = str_replace(' ', '', $string);
$explode = explode(',',$string);
$res = array_combine($explode,$explode);
echo '<pre>';
print_r($res);
echo '</pre>';
Or if you need to make lower case key for resulting array use following :
echo '<pre>';
print_r(array_change_key_case($res,CASE_LOWER));
echo '</pre>';
<?php
$string = 'Apple, Orange, Lemone'; // your string having space after each value
$string =str_replace(' ', '', $string); // removing blank spaces
$array = explode(',', $string );
$final_array = array_combine($array, $array);
$final_array = array_change_key_case($final_array, CASE_LOWER); // Converting all the keys to lower case based on your requiment
echo '<pre>';
print_r($final_array);
?>
You can use array functions such as array_combine, and array_values
$string = 'Apple, Orange, Lemone';
$arr = explode(', ', $string);
$assocArr = array_change_key_case(
array_combine(array_values($arr), $arr)
);
<?php
$string = 'Apple, Orange, Lemone';
$array = explode(', ', $string);
print_r($array);
output will be
Array
(
[0] => Apple
[1] => Orange
[2] => Lemone
)
Now
$ar = array();
foreach ($array as $value) {
$ar[$value] = $value;
}
print_r($ar);
Your Desire Output:
Array
(
[Apple] => Apple
[Orange] => Orange
[Lemone] => Lemone
)
$valuesInArrayWithSpace = explode("," $string);
$finalArray = [];
foreach ($ValuesInArrayWitchSpace as $singleItem) {
$finalArray[trim(strtolower($singleItem))] = trim($singleItem);
}
This way you'll have what you need:
$lowerString = strtolower($string);
$values = explode(', ', $string);
$keys = explode(', ', $lowerString);
$array = array_combine($keys, $values);
print_r($array);
Or...
$csvdata = str_getcsv('Apple,Orange,Lemone');
$arr = [];
foreach($csvdata as $a) {
$arr[strtolower(trim($a))] = $a;
}
print_r($arr);
use array_flip to change the values as key and use array_combine
<?php
$string = 'Apple, Orange, Lemone';
$array = explode(', ', $string);
$new_array =array_flip($array);
$final_array = array_combine($new_array,$array)
print_r($final_array );
?>
A clean, functional-style approach can use array_reduce() after splitting on commas followed by spaces.
Before pushing the new associative values into the result array, change the key to lowercase.
Code: (Demo)
$string = 'Apple, Orange, Lemone';
var_export(
array_reduce(
explode(', ', $string),
fn($result, $v) =>
$result + [strtolower($v) => $v],
[]
)
);
Output:
array (
'apple' => 'Apple',
'orange' => 'Orange',
'lemone' => 'Lemone',
)
I have an string
$str = 'one,,two,three,,,,,four';
I want to array like this(output of print_r)
Array ( [0] => one,two,three,four )
My code is
$str = 'one,,two,three,,,,,four';
$str_array = explode(',', $str);
print_r($str_array);
But not working Because multiple commas side by side.How can i solve this problem?
You can used array_filter function to removed empty element from array.
So your code should be:
$str = 'one,,two,three,,,,,four';
$str_array = array_filter(explode(',', $str));
print_r($str_array);
Edited Code
$str = 'one,,two,three,,,,,four';
$str_array = implode(',',array_filter(explode(',', $str)));
echo $str_array; // you will get one,two,three,four
You can remove multiple comma using preg_replace as
$str = 'one,,two,three,,,,,four';
echo $str_new = preg_replace('/,+/', ',', $str);// one,two,three,four
$str_array = explode(' ', $str_new);
print_r($str_array);//Array ( [0] => one,two,three,four )
try this
<?php
$string = 'one,,two,three,,,,,four';
$new_array = array_filter(explode(',', $string));
$final_array[] = implode(',',$new_array);
print_r($final_array);
?>
OUTPUT: Array ( [0] => one,two,three,four )
<?php
$string = 'one,,two,three,,,,,four';
$result = array(preg_replace('#,+#', ',', $string));
print_r($result);
Output:
Array ( [0] => one,two,three,four )
I have a text file with a lot of strings now i want to put those strings into a array.
I need to set between the screen quites "",
Text file is saved as,
String1
String2
String3
This most be
"String1", "String2, "String3"
Wat is the simplest way to do this in php/html/jquery ?
Try this:
Use file() to create an array from the lines of the text file, and array_map() to add the quotes:
$lines = file('myfile.txt');
$lines = array_map(function($x){return $x = '"'.$x.'"';}, $lines);
See this demo
in php simply use file() function
<?php
$array = file('file.txt');
http://php.net//manual/en/function.file.php
To get your array you'd use this:
$lines = explode("\n", $string);
Which returns:
Array
(
[0] => String1
[1] => String2
[2] => String3
)
EXAMPLE
Now the full example would look like this:
$lines = explode("\n", $string);
$a = array();
foreach($lines as $line) {
$a[] = "\"". trim($line) ."\"";
}
$string = implode(', ', $a);
print_r($a);
echo "String: " . $string;
That gives you the output of:
Array
(
[0] => "String1"
[1] => "String2"
[2] => "String3"
)
String: "String1", "String2", "String3"
EXAMPLE
This question already has answers here:
How to split a string by multiple delimiters in PHP?
(4 answers)
Closed 12 months ago.
Can we do multiple explode() in PHP?
For example, to do this:
foreach(explode(" ",$sms['sms_text']) as $no)
foreach(explode("&",$sms['sms_text']) as $no)
foreach(explode(",",$sms['sms_text']) as $no)
All in one explode like this:
foreach(explode('','&',',',$sms['sms_text']) as $no)
What's the best way to do this? What I want is to split the string on multiple delimiters in one line.
If you're looking to split the string with multiple delimiters, perhaps preg_split would be appropriate.
$parts = preg_split( '/(\s|&|,)/', 'This and&this and,this' );
print_r( $parts );
Which results in:
Array (
[0] => This
[1] => and
[2] => this
[3] => and
[4] => this
)
Here is a great solution I found at PHP.net:
<?php
//$delimiters must be an array.
function multiexplode ($delimiters,$string) {
$ready = str_replace($delimiters, $delimiters[0], $string);
$launch = explode($delimiters[0], $ready);
return $launch;
}
$text = "here is a sample: this text, and this will be exploded. this also | this one too :)";
$exploded = multiexplode(array(",",".","|",":"),$text);
print_r($exploded);
//And output will be like this:
// Array
// (
// [0] => here is a sample
// [1] => this text
// [2] => and this will be exploded
// [3] => this also
// [4] => this one too
// [5] => )
// )
?>
you can use this
function multipleExplode($delimiters = array(), $string = ''){
$mainDelim=$delimiters[count($delimiters)-1]; // dernier
array_pop($delimiters);
foreach($delimiters as $delimiter){
$string= str_replace($delimiter, $mainDelim, $string);
}
$result= explode($mainDelim, $string);
return $result;
}
You could use preg_split() function to stplit a string using a regular expression, like so:
$text = preg_split('/( |,|&)/', $text);
I'd go with strtok(), eg
$delimiter = ' &,';
$token = strtok($sms['sms_text'], $delimiter);
while ($token !== false) {
echo $token . "\n";
$token = strtok($delimiter);
}