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
Related
Suppose I have a string (which contain array of objects):
$string = "[{'test':'1', 'anothertest':'2'}, {'test':'3', 'anothertest':'4'}]";
My goals is to get the output to look like this when I print_r:
Array
(
[0] => Array
(
[test] => 1
[anothertest] => 2
)
[1] => Array
(
[test] => 3
[anothertest] => 4
)
)
I tried to json_decode($string) but it returned NULL
Also tried my own workaround which is kinda solved the problem,
$string = "[{'test':'1', 'anothertest':'2'}, {'test':'3', 'anothertest':'4'}]";
$string = substr($string, 1, -1);
$string = str_replace("'","\"", $string);
$string = str_replace("},","}VerySpecialSeparator", $string);
$arrayOfString = explode("VerySpecialSeparator",$string);
$results = [];
foreach($arrayOfString as $string) {
$results[] = json_decode($string, true);
}
echo "<pre>";
print_r($results);
die;
But is there any other ways to solve this?
As per your given data, if quotes will be corrected, then you will get your desired output, so get it done like below:
<?php
$string = "[{'test':'1', 'anothertest':'2'}, {'test':'3', 'anothertest':'4'}]";
$string = str_replace("'",'"', $string);
print_r(json_decode($string,true));
https://3v4l.org/PDI7O
I want to remove duplicates image. How to use array_unique? This is what I have tried:
$text = 'text image.jpg flower.jpg txt image.jpg';
$pattern = '/[\w\-]+\.(jpg|png|gif|jpeg)/';
$result = preg_match_all($pattern, $text, $matches);
$matches = $matches[0];
foreach ($matches as $klucz => $image) {
echo $image;
}
array_unique should be applied to an array. So split your string into chunks and use it:
$names = array_unique(explode(' ', $text));
First, explode() the string around " " then call array_unique(). Eg below:
$text = 'text image.jpg flower.jpg txt image.jpg';
$arr = explode(" ", $text);
$arr = array_unique($arr);
print_r($arr); // Array ( [0] => text [1] => image.jpg [2] => flower.jpg [3] => txt )
Read more:
explode()
array_unique()
I used preg_match because in the text the pictures are from the path
$text = 'text image.jpg flower.jpg txt <img src="path/image.jpg" '>;
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 )
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";