PHP while loop to read multiline text from string - php

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];
}

Related

How to split the string in array in 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

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);

How to read integers separated by space from a file in php

I am trying to read a line where multiple numbers were separated by space using php. Initially I tried using fscanf however the issue is, as fscanf read one line at a time, it only reads the first number. I am confused what to do.
Sample Input
20 30 -5987 456 523
The best approach for this case is to use a combination of explode and file reading. The strategy is initially read the whole line as an string. Then use explode to store the all the number in an array. However in that case the array would a string array later on we can change the type of array element from String to integer. Here is how
<?php
$_fp = fopen("php://stdin", "r");
fscanf($_fp, "%d\n", $count);
$numbers = explode(" ", trim(fgets($_fp)));
foreach ($numbers as &$number)
{
$number = intval($number);
}
sort($numbers);
?>
$input = trim(fgets(STDIN));
$arr = explode(" ", $input);
foreach($arr as &$number){
$number = (int)$number;
}
If you want to eliminate white space from "fopen" function user "trim" function or surround variable with trim function.
Example :
echo "Please enter series limit : ";
$handles = fopen ("php://stdin","r");
$n = trim(fgets($handles));
So here we can remove white space in between the characters as well as at the end.

search for the content of textarea1 in textarea2

how i can search for the content of textarea1 in textarea2 and print the whole line matches
example:
textarea1 contents(words)
content1
content2
content3
textarea2 contents(the lines)
this is content1
this is cont
this content3
so i want the printed matches lines like this
this is content1
this content 3
because content1 and content 3 in my textarea1
Here comes an example using preg_match(), note that the search strings have to be quoted by preg_quote():
$text1 = $_POST['text_area1'];
$text2 = $_POST['text_area2'];
// split search texts. in this case we use new line
$search = explode("\n", preg_quote($text1));
// now prepare for a regex
$regex = '~(' . implode('|', $search) . ')~';
// now split the text by newline
$lines = explode("\n", $text2);
foreach($lines as $line) {
if(preg_match($regex, $line)) {
print $line . "\n";
}
}
Output:
this is content1
this content3
Note that you may refine the way how you separate the search strings. In my example I split them by newline, but you may wish them additionally splitted by spaces or , ...
$textarea1 = "content1\ncontent2\ncontent3";
$chunks = explode("\n", $textarea1);
$textarea2 = "this is content1\nthis is cont\nthis is content3";
$lines = explode("\n", $textarea2);
foreach ($chunks as $c)
foreach ($lines as $l)
if (strpos($l, $c))
echo $l . '<br>';
To use regex in this case is a bit too much in my opinion, just use basic string-functions offered by php:
// the \n is the line break smybol used in the textarea
$needle = "content1\ncontent2\ncontent3"; // this text is probably received via $_GET['text1'] or something similar
$haystack = "this is content1\nthis is cont\nthis is content3";
// get all lines
$needle_lines = explode("\n", $needle);
$haystack_lines = explode("\n", $haystack);
foreach($haystack_lines as $hline) {
foreach ($needle_lines as $line) {
if (strpos($hline, $line) === false)
continue;
echo $hline."<br />";
//continue the outer foreach since we already found a match for the haystack_line
continue 2;
}
}
Update #1:
This code iterates through all lines in your haystack and checks for every needle in it.
If it finds one needle the line is printed via echo and we proceed with the next line of the haystack - is there anything more needed?

How do I edit this text file using PHP?

I do have a text file having around 400k data in it. and its content is like this..
1,james
2,mathew
3,yancy
4,brandon
5,molner
6,nick
7,neil...and so on
How do I remove numbers and comas from this text file and keep only names?
Read the file into an array, where each array item is one line. Walk throught the array, find the first comma, and remove it and everything before. Then write it all back out again.
// Warning! Brain-compiled code ahead.
$arr = file('myfile.txt');
foreach ( $arr as &$val )
$val = substr($val, strpos($val, ',') + 1);
file_put_contents('myoutfile.txt', implode(PHP_EOL, $arr));
Note - no error checking. If a line lacks a comma, or comma is the last character, chaos ensues.
400k isn't incredibly much, so you should get away with this (tested):
foreach (file($path) as $line)
print preg_replace("~^[0-9]+\,(.*)~", "$1", $line);
Here is a perl one liner that do the job:
perl -i.save -pe 's/^\d+,//' test.txt
The original file will be saved in test.txt.save
This is tested and will return it as a list but you can save it to a database if you want:
$file_path='my_file.txt';
$file_handler = fopen($file_path, 'rt');
$doc = fread($file_handler, filesize($file_path)+1);
$rows = explode("\n", $doc);
$rows_array = array();
foreach ($rows as $row) {
$data = explode(",", $row);
$return_array[] = $data[1];
}
//print_r($return_array);
//you can save it to a db
echo '<ul>';
foreach($return_array as $value){
echo '<li>'.$value.'</li>';
}
echo '</ul>';

Categories