PHP & HTML <a href> leaving extra space? - php

I have the following PHP code
$links = fopen("./links/links.txt", "r");
if ($links) {
while (($line = fgets($links)) !== false) {
$linkData = explode(" ", $line);
/// The line below is the problematic one
echo "<a href='".$linkData[0]."' class='links-item'>".$linkData[1]."</a><br>";
}
fclose($links);
} else {
die('Error opening file, try refreshing.');
}
You can see I've seperated the line I'm having issues with. I have the following file links.txt
http://example.com Example
http://example2.com Example2
Basically this will add the URL in the text file to an anchor tag, and it'll add the text next to it, as the anchor display text. It works, but for some reason, every anchor tag ends with a space, except the last one. Anyone know why this is and how I can fix it?

The string that fgets() returns includes the newline that separates the lines. This will be at the end of $linkData[1], so you're writing
<a href='http://example.com' class='links-item'>Example
</a><br>
to the output.
You could instead use fgetcsv(), specifying space as the field delimiter. This will explode the line for you and automatically ignores the newlines.
while (($linkData = fgetcsv($links, 0, " ")) !== false) {
echo "<a href='".$linkData[0]."' class='links-item'>".$linkData[1]."</a><br>";
}

fgets() captures newlines as well as word characters into the string. Use the trim function to remove unwanted whitespace:
echo "<a href='".trim($linkData[0])."' class='links-item'>".trim($linkData[1])."</a><br>";
Alternatively, as #Barmar noted, you could use fgetcsv function

use
var_dump($linkData);
To see what does fgets() returns. Maybe there are unexpected characters.
Consider to use more advanced file formatting, for example you can use csv format and use http://php.net/manual/en/function.fgetcsv.php to retrieve results from file.

Related

How to replace PHP code in a file having newlinse

I got some files to change by clicking a button. To go for it, i have the old string to replace, saved in database, and also the new one.
On the click button, it executes a function that is gonna find the old string in the PHP file, then gonna replace it by the new one. (Final goal is to automate the PHP edits in a web software after an update).
My problem is that it perfectly works on short strings (without newline), but as soon as there is a newline into the file, nothing happens.
This is my actual code :
$path = '/mypath/' . $item['path'];
$old_code = $item['old_code'];
$new_code = $item['new_code'];
}
$pos = strpos(file_get_contents($path), $old_code);
$file = file_get_contents($path);
$str = str_replace($old_code, $new_code, $file);
file_put_contents($path, $str);
$pos is "true" if my $old_code doesn't have any newline.
I tried to use preg_match to remove \n, but the problem is that when i'll have to push my edits on the file with file_put_contents, every newline will also disapear.
Example of non-working str_replace :
echo "ok"; echo 'hey there is some spaces before'
echo 'this is a sentence';
$menu = ['test1', 'test200'];
print_r($menu);
$url = "/link/to/test";
$div = "echo \"<div class='central_container' align='center'>\";";
Do you have any idea for resolving this ?
Thanks
if I`m not wrong str_replace() work only with single lines . Its have 2 options.
Option line replace str_replace() with preg_replace() or just use https://regex101.com/ there also have code generator after you finish you Regex

how to do echo from a string, only from values that are between a specific stretch[href tag] of the string?

[PHP]I have a variable for storing strings (a BIIGGG page source code as string), I want to echo only interesting strings (that I need to extract to use in a project, dozens of them), and they are inside the quotation marks of the tag
but I just want to capture the values that start with the letter: N (news)
[<a href="/news7044449/exclusive_news_sunday_"]
<a href="/n[ews7044449/exclusive_news_sunday_]"
that is, I think you will have to work with match using: [a href="/n]
how to do that to define that the echo will delete all the texts of the variable, showing only:
note that there are other hrefs tags with values that start with other letters, such as the letter 'P' : href="/profiles... (This does not interest me.)
$string = '</div><span class="news-hd-mark">HD</span></div><p>exclusive_news_sunday_</p><p class="metadata"><span class="bg">Czech AV<span class="mobile-hide"> - 5.4M Views</span>
- <span class="duration">7 min</span></span></p></div><script>xv.thumbs.preparenews(7044449);</script>
<div id="news_31720715" class="thumb-block "><div class="thumb-inside"><div class="thumb"><a href="/news31720715/my_sister_running_every_single_morning"><img src="https://static-hw.xnewss.com/img/lightbox/lightbox-blank.gif"';
I imagine something like this:
$removes_everything_except_values_from_the_href_tag_starting_with_the_letter_n = ('/something regex expresion I think /' or preg_match, substring?);
echo $string = str_replace($removes_everything_except_values_from_the_href_tag_starting_with_the_letter_n,'',$string);
expected output: /news7044449/exclusive_news_sunday_
NOTE: it is not essential to be through a variable, it can be from a .txt file the place where the extracts will be extracted, and not necessarily a variable.
thanks.
I believe this will help her.
<?php
$source = file_get_contents("code.html");
preg_match_all("/<a href=\"(\/n(?:.+?))\"[^>]*>/", $source, $results);
var_export( end($results) );
Step by Step Regex:
Regex Demo
Regex Debugger
To get just the links out of the $results array from Valdeir's answer:
foreach ($results as $r) {
echo $r;
// alt: to display them with an HTML break tag after each one
echo $r."<br>\n";
}

Why does it add the text at the beginning of next line, and not the end of the right one?

Needed solution:
I am working with a simple PHP script that should:
Add "value4:::" at the end of the first line in a file
Add ":::" at the end of all the next lines
I am novise in programming, and have sit here for two days trying to figure this out. Might be a little detail, or it might be totally wrong way of doing this task.
It might be wrong way to do this, or may be a regex problem? I really don't know.
I kindly ask you to help me with the solution.
Information:
The file newstest.db looks like this:
ID:::value1:::value2:::value3:::
1:::My:::first:::line:::
2:::My:::second:::line:::
3:::Your:::third:::line:::
And using this php script I'd like to make it look like this:
ID:::value1:::value2:::value3:::value4:::
1:::My:::first:::line::::::
2:::My:::second:::line::::::
3:::Your:::third:::line::::::
Problem:
So far I have almost got it, but I am confused to why it adds the "value4:::" to the beginning of the second line, and then add ":::" at the beginning (not end) of all of the rest of the lines.
So I get a file that looks like this:
ID:::value1:::value2:::value3:::
value4:::1:::My:::first:::line:::
:::2:::My:::second:::line:::
:::3:::Your:::third:::line:::
I thought that:
$lineshere = 'Some text here:::';
$lines1 = $linehere.'value4:::';
would output "Some text here:::value4:::"
May be the problem is due to this way of adding line after line?
$lines = '';
$lines.= 'My test';
$lines.= ' is here';
echo $lines;
I am a novise in programming, so I might have used totally wrong functions tec to make this work.
But in this case it seams to add a space or line break/ line end in the wrong place.
My try on this solution:
<?php
// specify the file
$file_source="newstest.db";
// get the content of the file
$newscontent = file($file_source, true);
//set a start value (clear memory)
$lines ='';
// get each line and treat it line by line.
foreach ($newscontent as $line_num => $linehere) {
// add "value4:::" at the end of FIRST line only, and put it in memory $lines
if($line_num==0) {
$lines.= $linehere.'value4:::';
// Just to see what the line looks like
//echo 'First line: '.$lines.'<br /><br />';
}
// then add ":::" to the other lines and add them to memory $lines
if($line_num>0) {
$lines1 = $linehere.':::';
$lines.= $lines1;
//just look at the line
//echo 'Line #'.$line_num.': '.$lines1.'<br /><br />';
}
}
//Write new content to $file_source
$f = fopen($file_source, 'w');
fwrite($f,$lines);
fclose($f);
echo "// to show the results ar array<br /><br />";
$newscontentlook = file($file_source, true);
print_r(array_values($newscontentlook));
?>
This is actually very easy to achieve with file_get_contents and preg_replace, i.e:
$content = file_get_contents("newstest.db");
$content = preg_replace('/(^ID:.*\S)/im', '$1value4:::', $content);
$content = preg_replace('/(^\d+.*\S)/im', '$1:::', $content);
file_put_contents("newstest.db", $content);
Output:
ID:::value1:::value2:::value3:::value4:::
1:::My:::first:::line::::::
2:::My:::second:::line::::::
3:::Your:::third:::line::::::
Ideone Demo
the function file() gives you the file in an array with each line being an element of the array. Each ending of the line (EOL) is included in the elements. So appending text to that line will be after the EOL, and thus effectively on the beginning of the next line.
You can either choose to not use file() and explode the text yourself on the EOL, so the EOL is no longer part of the array element. Then edit the elements, and implode the array again.
Or fopen() the file, and fread() through it yourself. The latter option is preferred, as it won't load the entire file into memory at once.
I think the problem is in your loop through the lines read by file() function:
foreach ($newscontent as $line_num => $linehere) {
...
$linehere contains a newline at the end, so you should simply chop it before using it:
foreach ($newscontent as $line_num => $linehere) {
$linehere = chop($linehere);
...
If you don't chop the line contents, when you concatenate a string to it, you'll get:
LINE_CONTENTS\nSTRING_ADDED
which, when printed, will be:
LINE_CONTENTS
STRING_ADDED
Hope this helps...

PHP wont recognise double line feed

I am running a RST to php conversion and am using preg_match.
this is the rst i am trying to identify:
An example of the **Horizon Mapping** dialog box is shown below. A
summary of the main features is given below.
.. figure:: horizon_mapping_dialog_horizons_tab.png
**Horizon Mapping** dialog box, *Horizons* tab
Some of the input values to the **Horizon Mapping** job can be changed
during a Workflow using the internal programming language, IPL. For
details, refer to the *IPL User Guide*.
and I am using this regex:
$match = preg_match("/.. figure:: (.*?)(\n{2}[ ]{3}.*\n)/s", $text, &$result);
however it is returning as false.
here is a link of the expression working on regex
http://regex101.com/r/oB3fW7.
Are you sure that the line break is \n, is doubt, use \R:
$match = preg_match("/.. figure:: (.*?)(\R{2}[ ]{3}.*\R)/s", $text, &$result);
\R stands for either \n, \r and \r\n
My instinct would be to do some troubleshooting around the s flag as well as the $result variable passed by reference. To achieve the same without any interference from dots and the return variable, can you please try this regex:
..[ ]figure::[ ]([^\r\n]*)(?:\n|\r\n){2}[ ]{3}[^\r\n]*\R
In code, please try exactly like this:
$regex = "~..[ ]figure::[ ]([^\r\n]*)(?:\n|\r\n){2}[ ]{3}[^\r\n]*\R~";
if(preg_match($regex,$text,$m)) echo "Success! </br>";
Finally:
If this does not working, you might have a weird Unicode line break that php is not catching. To debug, for each character of your string, iterate through all the string's characters
Iterate: foreach(str_split($text) as $c) {
Print the character: echo $c . " value = "
Print the value from this function: . _uniord($c) . "<br />"; }

Using PHP to Seperate Results of a txt file

I am trying to display the last 10 lines of a File and from there take those results and break them down to 10 individual lines..
Currently the code I have found from examples is:
$filearray = file("test.txt");
$lastfifteenlines = array_slice($filearray,-10);
echo implode($lastfifteenlines, "\n")
It display's the 10 items I need however it does not break them down onto individual lines the current results are:
1.0.0.11 1.0.0.12 1.0.0.13 1.0.0.14 1.0.0.15
I need that to instead display as:
1.0.0.11
1.0.0.12
1.0.0.13
1.0.0.14
1.0.0.15
Thanks in Advance for the Asistance!
\n is plain whitespace in html.
use echo implode("<br>", $lastfifteenlines) or put them in to separate divs, use a list (ul+li), etc..
use the explode function, like this
$filearray = file("test.txt");
$lastfifteenlines = array_slice($filearray,-10);
$impfile = implode($lastfifteenlines, '\n');
$lines = explode('\n', $impfile);
foreach ($lines as $line){
echo $line."<br>";
}
outpu will be
1.0.0.11
1.0.0.12
1.0.0.13
1.0.0.14
1.0.0.15
i hope that's what you want :)
Your code works fine. You just can't see the line breaks because HTML doesn't treat them as line breaks.
See the HTML source code in your browser to see the line breaks.
Possible solution
echo <pre> and </pre> tags before and after the implode.
Add header("Content-Type: text/plain"); before any output. It will cause the browser to parse the document as a text file and not HTML (note that no HTML tags will be parsed by the browser)
implode the array with a different string, <br>, which will cause a line break in HTML.
Also, your syntax is wrong, it's
implode($glue, $pieces);
And not
implode($pieces, $glue);

Categories