.txt date on HTML website, explode() - php

I've got a "data.txt" file with the following content:
One1:One2:One3:One4:One5:One6
Two1:Two2:Two3:Two4:Two5:Two6
Three1:Three2:Three3:Three4:Three5:Three6
Now I want to be able to take each data and put on a specific location of a htlm code. Each line for its own. So for the first line, it should look something like this:
<html>
<head>
<title></title>
<head>
<body>
<h1>One2</h1>
<h2>One4 some other Text One5</h2>
<img src="One6.jpg">
</body>
</html>
Unforturtunately I don't have a clue how to do that with explode(). Can anybody help me out or does someone know a good and easy tutorial?
Thanks a lot

Not completely sure if I got your question, but I think you want to first parse the data.txt line by line, THEN by the : delimiter.
$lines = file("data.txt", FILE_IGNORE_NEW_LINES);
foreach($lines as $line)
{
$split = explode(":", $line);
$s1 = $split[0];
$s2 = $split[1];
$s3 = $split[2];
echo '<h1>'.$s1.'</h1>';
echo '<h2>'.$s2.' lorem ipsum</h2>';
echo '<img src="'.$s3.'">';
}
Or would you like to output different content based on what line its currently reading from? Then something like:
$lines = file("data.txt", FILE_IGNORE_NEW_LINES);
$n = count($lines);
for($i=0; $i<$n; $i++)
{
$split = explode(":", $lines[$i]);
$s1 = $split[0];
$s2 = $split[1];
$s3 = $split[2];
if($i === 0)
{
echo 'First line in data.txt<br>';
}
elseif($i === 1)
{
echo 'Second line in data.txt<br>';
}
elseif($i === 2)
{
echo 'Third line in data.txt<br>';
}
else
{
echo 'All the other lines (which are currently not existing)<br>';
}
}
Just kind of guessing here, could need some more information to clarify the question :)

Related

How can I remove certain lines in a multiline string?

My code is receiving a string which I have no control of, which I'll call $my_string. The string is the contents of a transcript. If I echo the string, like so:
echo $my_string;
I can see the contents, which look something like this.
1
00:00:00.000 --> 00:00:04.980
[MUSIC]
2
00:00:04.980 --> 00:00:08.120
Hi, my name is holl and I am here
to write some PHP.
3
00:00:08.120 --> 00:00:10.277
You can see my screen, here.
What I'd like to do is run this through a function so it's just the actual words spoken, removing all the lines that signify time, or the order.
[MUSIC]
Hi, my name is holl and I am here
to write some php.
You can see my screen, here.
My idea is to explode the whole string by the break, and try to detect which lines which are either empty or start with a number, like so...
$lines = explode("\n", $my_string);
foreach ($lines as $line) {
if (is_numeric(line[0]) || empty(line[0]) ) {
continue;
}
$exclude[] = $line;
}
$transcript = implode("\n", $exclude);
But the result of this action is exactly the same- the output has numbers and blank lines. I clearly misunderstand something- but what is it? And is there a better way of trying to achieve my goal?
Thanks!
EDIT: Removed an echo where I wasn't actually using one in my code.
The problem is that you use indexing on $line:
$lines = explode("\n", $my_string);
foreach ($lines as $line) {
if (is_numeric(line[0]) || empty(line[0]) ) {//index usage?
continue;
}
$exclude[] = $line;
}
$transcript = echo implode("\n", $exclude); //remove echo
replace by:
$lines = explode("\n", $my_string);
foreach ($lines as $line) {
if (is_numeric($line) || empty($line) ) {//here
continue;
}
$exclude[] = $line;
}
$transcript = implode("\n", $exclude);
You also need regex matching to remove the 00:00:00.000 --> 00:00:04.980 fragments.
You can combine them by:
if(preg_match('/^(|\d+|\d+:\d+:\d+\.\d+\s+-->\s+\d+:\d+:\d+\.\d+)$/',$line)) { //regex
takes all possibilities into account:
$lines = explode("\n", $my_string);
foreach ($lines as $line) {
if(preg_match('/^(|\d+|\d+:\d+:\d+\.\d+\s+-->\s+\d+:\d+:\d+\.\d+)$/',$line)) {
continue;
}
$exclude[] = $line;
}
$transcript = implode("\n", $exclude);
echo $transcript;
Example (with php -a):
$ php -a
php > $my_string='1
php ' 00:00:00.000 --> 00:00:04.980
php ' [MUSIC]
php '
php ' 2
php ' 00:00:04.980 --> 00:00:08.120
php ' Hi, my name is holl and I am here
php ' to write some PHP.
php '
php ' 3
php ' 00:00:08.120 --> 00:00:10.277
php ' You can see my screen, here.';
php > $lines = explode("\n", $my_string);
php > foreach ($lines as $line) {
php { if(preg_match('/^(|\d+|\d+:\d+:\d+\.\d+\s+-->\s+\d+:\d+:\d+\.\d+)$/',$line)) {
php { continue;
php { }
php { $exclude[] = $line;
php { }
php > $transcript = implode("\n", $exclude);
php > echo $transcript;
[MUSIC]
Hi, my name is holl and I am here
to write some PHP.
You can see my screen, here.
Your code works almost. Just forgot $ in line[0] and " " is not empty().
$my_string = <<< EOF
1
00:00:00.000 --> 00:00:04.980
[MUSIC]
2
00:00:04.980 --> 00:00:08.120
Hi, my name is holl and I am here
to write some PHP.
3
00:00:08.120 --> 00:00:10.277
You can see my screen, here.
EOF;
$lines = explode("\n", $my_string);
foreach ($lines as $line) {
$temp = trim($line[0]);
if (is_numeric($temp) || empty($temp) ) {
continue;
}
$exclude[] = $line;
}
$transcript = implode("\n", $exclude);
echo $transcript;
Result:
[MUSIC]
Hi, my name is holl and I am here
to write some PHP.
You can see my screen, here.
It looks like it's a pattern. That is every first and second line contain meta data, the third is text, and the fourth is empty. If that is indeed the case, it should be trivial. You don't have to check the content at all and just grab the third line of every quartet:
$lines = explode("\n", $my_string);
$texts = array();
for ($i = 0; $i < count($lines); $i++) {
if ($i % 4 == 2) { // Index of third line is 2, of course.
$texts[] = $lines[i];
}
}
$transcript = implode($texts, "\n");
With alternative logic, because as you rightfully mentioned there can be more than one line of text, you could say that blocks/entries whatever you call them, are separated by an empty line. Each block starts with two lines of meta data, followed by one (or maybe zero) or more lines of text. With that logic you could parse it like this:
$lines = explode("\n", $my_string);
$texts = array();
$linenr = 0;
foreach ($lines as $line) {
// Keep track of the how manieth non-empty line it is.
if ($line === '')
$linenr = 0;
else
$linenr++;
// Skip the first two lines of a block.
if ($linenr > 2)
$texts[] = $line;
}
$transcript = implode($texts, "\n");
I don't know this particular format, but if I wanted to do this, I would be eager to find a pattern like this rather than parse the lines themselves. It looks like a script or subtitle file, and if you want to turn it into a transcript, it would be a shame if somebody shouted '300' and it would not be transcripted.
to remove theses lines try to use : preg_replace + regex
php man [1]: http://php.net/manual/en/function.preg-replace.php

Php Unexpected T_FOR, expecting ). Creating multi-dimensional arrays using for()

here is my code. What I am trying to achieve is get text like this
Hola Hi
Pollo Chicken
Queso Cheese
and so on, and be able to make an array out of it such that
array[0][1] is Hi.
here is my code, the error is on line 13
<?php
if(isset($_POST['submit'])){
$message = $_POST['text'];
$words2 = explode("\r\n", $message);
$words = explode("\t", $words2[0]);
$numberoflines = count($words2);
echo $numberoflines;
for($i=0; $i<$numberoflines; $i++){
$words[$i] = $line;
$arrayline = explode("\t", $line);
$cow = array(
for($u=0; $u<2; $u++){
array($arrayline[$u])
}
);
}
}
?>
<html>
<form method = "POST" method ="changetext.php">
<textarea name="text">
</textarea>
<input type="submit" value = "Flip!" name="submit">
</form>
</html>
Maybe thats what you wanted to achieve ?!?
for($i=0; $i<$numberoflines; $i++){
$arraycols= explode("\t", $words[$i]);
foreach($arraycols as $col){
$list[$i][] = $col;
}
}
so Array $list is $list[row][col]
if i got right what is inside the $words Array. Your code is a little messi ;)
Try something like this:
$words = array();
if(isset($_POST['submit'])){
// Break down the text as lines:
$lines = explode("\r\n", $_POST['text']);
// For every line...
foreach($lines as $line){
// Seperate the 2 words (seperated by a tab)
$words[] = explode("\t", $line);
}
// Print the result:
var_dump($words);
}

PHP Read a number from a txt file and make then calculations

I have a file which has only one line, with a number from 1 to 40, and I have the following code:
$file_line = file('../countersaver.txt');
foreach ($file_line as $line) {
$line_result = $line;
}
echo $line;
I have to calculate the result of $line - 1 and echo that result.
But when i do:
$line = $line - 1;
Then it shows $line - 1 and doesn't actually do the calculation.
Your code is weak to changes of the file contents. If someone adds a few blank lines, for example, your code won't work. Try this out instead:
$number = trim(file_get_contents('../countersaver.txt'));
echo $number - 1;
Try replacing
$line = $line - 1;
echo $line
with
$line = ($line -1);
echo $line
This will print 19 instead of 20-1.
I don't see an approved answer here but for anyone looking at this post, if you have a variable that you want PHP to read as a number you can use intval() function. Details covered here...
http://php.net/manual/en/function.intval.php
Try this:
$fin = #fopen("path to file", "r");
if ($fin) {
while (!feof($fin)) {
$buffer = fgets($fin);
}
fclose($fin);
}

Reformatting The Content Of A File

I have a file called "data.txt". In this file, there are 30 lines with strings who all have the same length. It looks like this:
2QA4ZRDUT
IDVLTLZSC
4GYC3HCMV
1W6409JD5
70P7U66TE
... and so on.
What I want to do now is reformatting these lines. I want 5 strings on one line, seperated with a ";". After that, I want a new line and the next 5. In the end, it should look like this:
2QA4ZRDUT;IDVLTLZSC;4GYC3HCMV;1W6409JD5;70P7U66TE;
NGN1TGF6G;JWVI7LSIZ;U99TMVXXK;KLBDMRPQV;MEFKLUO3;
... and so on, until the whole content of the file is reformatted like this.
The last hours I've been trying to accomplish this by using for, foreach and while loops but I only manage to get one line. I hope somebody can help me since I'm not that experienced with PHP.
This is the content of "data.txt":
2QA4ZRDUT
IDVLTLZSC
4GYC3HCMV
1W6409JD5
70P7U66TE
OG2JBBZF6
5391PHOVW
ZAJ3OZ4H2
GMOB9E9X7
Q8U4C8ZK1
0WDZLRWWJ
N487W3S24
PKXQFFEK3
NSMKC29IB
HOLI1T2ZB
DVPIVLLLS
FH7RSZWTM
9VSUWPZEX
NM6ZWV19I
NGN1TGF6G
JWVI7LSIZ
U99TMVXXK
KLBDMRPQV
MEFKLUO3L
LICFIK24W
ELGPLCK51
QQS4SOJV1
KJ2UVTU1B
FLQ6T7LG6
QJZLAPYN1
something like that:
<?php
$oldf=fopen('data.txt','r');
$newf=fopen('data_new.txt','w');
$i=0;
while(!feof($oldf))
{
$i++;
$line=fgets($oldf);
fwrite($newf,$line.';');
if($i%5==0)
fwrite($newf,"\n");
}
fclose($oldf);
fclose($newf);
Try this:
<?php
$file_name = "test.txt"; // Change file name as needed
$file_data = file_get_contents($file_name);
$file_data_array = explode('\n', $file_data);
$i = 0;
$new_file_data = "";
foreach ($file_data_array as $piece)
{
$new_file_data .= $piece . ';';
$i++;
if ($i % 5 == 0) // Change number of pieces you want on a line as needed
{
$new_file_data .= '\n';
}
}
file_put_contents($file_name, $new_file_data);
?>
This should do it:
$str = '2QA4ZRDUT
IDVLTLZSC
4GYC3HCMV
1W6409JD5
70P7U66TE
OG2JBBZF6
5391PHOVW
ZAJ3OZ4H2
GMOB9E9X7
Q8U4C8ZK1
0WDZLRWWJ
N487W3S24
PKXQFFEK3
NSMKC29IB
HOLI1T2ZB
DVPIVLLLS
FH7RSZWTM
9VSUWPZEX
NM6ZWV19I
NGN1TGF6G
JWVI7LSIZ
U99TMVXXK
KLBDMRPQV
MEFKLUO3L
LICFIK24W
ELGPLCK51
QQS4SOJV1
KJ2UVTU1B
FLQ6T7LG6
QJZLAPYN1';
$arr = explode(PHP_EOL, $str);
$c = 1;
$str3 = '';
foreach ($arr as $item) {
$str3.= $item.';';
if ($c % 5 == 0) {
$str3.= PHP_EOL;
}
++$c;
}
echo "<p>$str3</p>";
Be aware that you won't see the line breaks in the browser, but they will be apparent when you 'view source'.
Edit: I'm using PHP_EOL here instead of "\n" as the other answers have suggested. This ensures that the script will work correctly on any platform (Win, MacOS & *nix) as long as the PHP setting auto_detect_line_endings is set to true

Help with string parsing

I have a huge library file containing a word and it's synonyms, this is some words and their synonyms in the format of my library:
aantarrão|1
igrejeiro|igrejeiro|aantarrão|beato
aãsolar|1
desolar|desolar|aãsolar|afligir|arrasar|arruinar|consternar|despovoar|devastar|magoar
aba|11
amparo|amparo|aba|abrigo|achego|acostamento|adminículo|agasalho|ajuda|anteparo|apadrinhamento|apoio|arrimo|asilo|assistência|auxíjlio|auxílio|baluarte|bordão|broquel|coluna|conchego|defesa|égide|encosto|escora|esteio|favor|fulcro|muro|patrocínio|proteção|proteçâo|resguardo|socorro|sustentáculo|tutela|tutoria
apoio|apoio|aba|adesão|adminículo|amparo|aprovação|arrimo|assentimento|base|bordão|coluna|conchego|descanso|eixo|encosto|escora|espeque|fé|fulcro|proteçâo|proteção|refúgio|socorro|sustentáculo
beira|beira|aba|beirada|borda|bordo|cairel|encosta|extremidade|falda|iminência|margem|orla|ourela|proximidade|rai|riba|sopé|vertente
beirada|beirada|aba|beira|encosta|falda|margem|sopé|vertente
encosta|encosta|aba|beira|beirada|clivo|falda|lomba|sopé|subida|vertente
falda|falda|aba|beira|beirada|encosta|fralda|sopé|vertente
fralda|fralda|aba|falda|raiss|raiz|sopé
prestígio|prestígio|aba|auréola|autoridade|domínio|força|halo|importância|influência|preponderância|valia|valimento|valor
proteção|proteção|aba|abrigo|agasalho|ajuda|amparo|apoio|arrimo|asilo|auspiciar|auxílio|bafejo|capa|custódia|defesa|égide|escora|fautoria|favor|fomento|garantia|paládio|patrocínio|pistolão|quartel|refúgio|socorro|tutela|tutoria
sopé|sopé|aba|base|beira|beirada|encosta|falda|fralda|raiz|vertente
vertente|vertente|aba|beira|beirada|declive|encosta|falda|sopé
see aantarrão is a word and below it are the synonyms, I can't think of a way to get the word and the synonyms on an associative array, this is what I'm trying to do:
<?
$file = file('library.txt');
$array_sinonimos = array();
foreach($file as $k)
{
$explode = explode($k, "|");
if(is_int($explode[1]))
{
$word = $explode[0];
}
}
?>
nothing, lol, what can I do here ? loop lines until I find an empty line then try to get a new word with the explode ?, help !
Here's some code I cooked up that seems to work.
See the code in action here: http://codepad.org/TVpYgW91
See the code here
UPDATED to read line by line
<?php
$filepointer = fopen("library.txt", "rb");
$words = array();
while(!feof($filepointer)) {
$line = trim(fgets($filepointer));
$content = explode("|", $line);
if (count($content) == 0)
continue;
if (is_numeric(end($content))) {
$word = reset($content);
continue;
}
if (isset($words[$word]))
$words[$word] = array_merge($words[$word], $content);
else
$words[$word] = $content;
}
print_r($words);
So what's the strategy?
fix up the line endings
run through the file line by line
ignore empty lines (count($content))
split the line up on the pipes, if the line has a numerical value for the last value, then this becomes our word
we only get to the last step if none of the other traps got touched, because of the continue statements, so if it is then just split up the words by the pipe and add them to or create the array element.
Try this. I can't remember if array_merge() will work with a null, but the basic idea is that $word is the $key to the assoc array.
<?
$file = file('library.txt');
$array_sinonimos = array();
foreach($file as $k)
{
$explode = explode($k, "|");
if(is_int($explode[1]))
{
$word = $explode[0];
}
else if(!empty($explode))
{
$array_sinonimos[$word] = array_merge($synonyms[$word], $explode);
}
}
?>

Categories