How to split the string in array in php - php

Can you tell me how i can split the below string in respective array
Here is the string:
ujjwal;23
33334;14
pendrive;20
Now I want to put above string into array like this:
array([0]=>ujjwal,[1]=>33334,[2]=>pendrive)
ignoring the number or string after semi-colon ; , please help me

You can simply use explode() PHP function to split the string by ;.
First you need to split the string by \n and then iterate over line by line and split by ;. And append the first element of the array in final array.
Code would look something like this,
<?php
$str="ujjwal;23
33334;14
pendrive;20";
$lines=explode("\n",$str);
$farray=array();
foreach($lines as $line) {
$linearray=explode(";",$line);
$farray[]=$linearray[0];
}
print_r($farray);
Demo: https://eval.in/641849

Assuming thats in a file?
$lines = file($file);
foreach($lines as $line){
$elements = explode(';', $line);
$array[] = $elements[0];
}

try this,
$new_array = array();
$string = "ujjwal;23 33334;14 pendrive;20";
// if string is not in single line then use explode("\n",$string );
$temp_array = explode(" ",$string);
foreach($temp_array as $val)
{
$new_array[] = strtok($val, ';');
}
print_r($new_array);
OUTPUT
Array
(
[0] => ujjwal
[1] => 33334
[2] => pendrive
)
DEMO

Related

How to convert a certain type of string into an array with keys in php?

I have a string of this type:
string(11) "2=OK, 3=OK"
from a text file. But I would like to convert it into an array of keys this type :
array (
[2] => Ok
[3] => Ok
)
I was wondering how we could do that in PHP.
Note:- I normally use explode() and str_split() for the conversions string into array but in this case I don't know how to do it.
use explode(), foreach() along with trim()
<?php
$string = "2=OK, 3=OK" ;
$array = explode(',',$string);
$finalArray = array();
foreach($array as $arr){
$explodedString = explode('=',trim($arr));
$finalArray[$explodedString[0]] = $explodedString[1];
}
print_r($finalArray);
https://3v4l.org/ZsNY8
Explode the string by ',' symbol. You will get an array like ['2=OK', ' 3=OK']
Using foreach trim and explode each element by '=' symbol
You can use default file reading code and traverse it to achieve what you want,
$temp = [];
if ($fh = fopen('demo.txt', 'r')) {
while (!feof($fh)) {
$temp[] = fgets($fh);
}
fclose($fh);
}
array_walk($temp, function($item) use(&$r){ // & to change in address
$r = array_map('trim',explode(',', $item)); // `,` explode
array_walk($r, function(&$item1){
$item1 = explode("=",$item1); // `=` explode
});
});
$r = array_column($r,1,0);
print_r($r);
array_walk — Apply a user supplied function to every member of an array
array_map — Applies the callback to the elements of the given arrays
explode — Split a string by a string
Demo.
You can use preg_match_all along with array_combine, str_word_count
$string = "2=OK, 3=OK" ;
preg_match_all('!\d+!', $string, $matches);
$res = array_combine($matches[0], str_word_count($string, 1));
Output
echo '<pre>';
print_r($res);
Array
(
[2] => OK
[3] => OK
)
LIVE DEMO

How to extract string between two slashes php

i know that its easy to extract string between two slashes using explode() function in php, What if the string is like
localhost/used_cars/search/mk_honda/md_city/mk_toyota
i want to extract string after mk_ and till the slashes like:** honda,toyota **
any help would be highly appreciated.
I am doing like this
echo strpos(uri_string(),'mk') !== false ? $arr = explode("/", $string, 2);$first = $arr[0]; : '';
but not working because if user enter mk_honda in any position then explode() is failed to handle that.
Use regex:
http://ideone.com/DNHXsf
<?php
$input = 'localhost/used_cars/search/mk_honda/md_city/mk_toyota';
preg_match_all('#/mk_([^/]*)#', $input, $matches);
print_r($matches[1]);
?>
Output:
Array
(
[0] => honda
[1] => toyota
)
Explode your string by /, then check every element of array with strpos:
$string = 'localhost/used_cars/search/mk_honda/md_city/mk_toyota';
$parts = explode('/', $string);
$r = [];
foreach ($parts as $p) {
// use `===` as you need `mk_` in position 0
if (strpos($p, 'mk_') === 0) {
// 3 is a length of `mk_`
$r[] = substr($p, 3);
}
}
echo'<pre>',print_r($r),'</pre>';
Just try this
$str='localhost/used_cars/search/mk_honda/md_city/mk_toyota';
$str=explode('/',$str);
$final=[];
foreach ($str as $words){
(!empty(explode('_',$words)))?(isset(explode('_',$words)[1]))?$final[]=explode('_',$words)[1]:false:false;
}
$final=implode(',',$final);
echo $final;
It give output as
cars,honda,city,toyota

PHP while loop to read multiline text from string

I have a multiline string and that have 2 words in line.
I want within a while loop while reading the script line by line
get the 1st word and 2nd word.
$multilinestring="name1 5
name2 8
name3 34
name5 55 ";
The result i want to have while i am reading the the string line by line is to get
2 more strings
$firstword and $secondword
Thank you all in advance!
Use this:
$eachLine = explode(PHP_EOL, $multilinestring); // best practice is to explode using EOL (End Of Line).
foreach ($eachLine as $line) {
$line = explode(" ", $line);
$firstword = $line[0];
$secondword = $line[1];
}
What's the point in using a while loop to do this? Use foreach loop to achieve this:
foreach (explode("\n", $multilinestring) as $line) {
$line = explode(" ", $line);
print_r($line);
}
If this is really a text file you want to read, then you'd be better of to use fgets() or read the file to an array completely with file() and use explode() afterwards. Consider this code:
$arr = file("somefile.txt"); // read the file to an array
for ($i=0;$i<count($arr);$i++) { // loop over it
$tmp = explode(" ", $arr[$i]); // splits the string, returns an array
$firstword = $tmp[0];
$secondword = $tmp[1];
}

Read from file and create associative array?

I am able to read from a file and create an array however I get the following error: Notice: Undefined offset: 1. Within my array there is one element that is empty and I don't understand why it is empty.
My text file is in the following format:
#EXTINF:0,ABC family USA[]http://localhost/IpInfo/index.html
#EXTINF:0,CBC[]http://localhost/IpInfo/index1.html
#EXTINF:0,A&E[]http://localhost/IpInfo/index2.html
Here is my code:
$fh = fopen('file1.txt', 'r');
$theData = fread($fh, filesize('file1.txt'));
$arr = array();
$my_array = explode("\r\n", $theData);
foreach($my_array as $line){
$tmp = explode("[]", $line);
$arr[$tmp[0]] = $tmp[1];
}
fclose($fh);
echo '<pre>';
echo print_r($arr);
I'm not quite sure what the problem is? Any help would be much appreciated!
Thanks!
Probably your input data doesn't use \r\n as the line delimiter? I'm not sure whether I got the problem completely. Also you might want to take empty lines into account.
I would use the file() function, which simplifies to iterate over the lines of a file and can handle Windows and Unix line feeds and check for empty lines:
$arr = array();
foreach(file('a.txt') as $line){
// I'm using `trim()` here since $line
// will still contain the newline delimiter
$line = trim($line);
// Skip empty lines
if(empty($line) {
continue;
}
$tmp = explode("[]", $line);
$arr[$tmp[0]] = trim($tmp[1]);
}
echo '<pre>';
print_r($arr);
Output:
<pre>Array
(
[#EXTINF:0,ABC family USA] => http://localhost/IpInfo/index.html
[#EXTINF:0,CBC] => http://localhost/IpInfo/index1.html
[#EXTINF:0,A&E] => http://localhost/IpInfo/index2.html
)
The reason is that the explode function splits your read-in data at the "\r\n". And you have a new line after the last line, and that's what results in the last "array" with no keys or values. To fix this, replace this line : $my_array = explode("\r\n", $theData); with these:
$my_array = explode("\r\n", $theData);
array_pop($my_array);

explode two-item-list in array as key=>value

I'd like to explode a multi-line-string like this
color:red
material:metal
to an array like this
$array['color']=red
$array['material']=metal
any idea?
Use explode(), you can use a regexp for it, but it's simple enough without the overhead.
$data = array();
foreach (explode("\n", $dataString) as $cLine) {
list ($cKey, $cValue) = explode(':', $cLine, 2);
$data[$cKey] = $cValue;
}
As mentioned in comments, if data is coming from a Windows/DOS environment it may well have CRLF newlines, adding the following line before the foreach() would resolve that.
$dataString = str_replace("\r", "", $dataString); // remove possible \r characters
The alternative with regexp can be quite pleasant using preg_match_all() and array_combine():
$matches = array();
preg_match_all('/^(.+?):(.+)$/m', $dataString, $matches);
$data = array_combine($matches[1], $matches[2]);
Try this
$value = '1|a,2|b,3|c,4|d';
$temp = explode (',',$value);
foreach ($temp as $pair)
{
list ($k,$v) = explode ('|',$pair);
$pairs[$k] = $v;
}
print_r($pairs);
explode first on line break. Prolly \n
Then explode each of the resulting array's items on : and set a new array to that key/value.

Categories