How do you remove the new line code ( ) with php? - php

Ok, so I was tasked with created a gallery, using a sql table is not an option, so I am doing what I can. This is my code, wich works fine, but it generates a hidden character at the end of every imate.
<?php
$photos = file("/elements/photos.php");
for ($i = 0; $i < count($photos); $i++) {
$allimages .= $imagefile = '<img src="/elements/photos/'.$photos[$i].'">';};
?>
<?=$allimages?>
This is the code that it generates
<img src="/elements/photos/t/a_little_kitten.jpg
">
I have been unable to find what
this means, I believe it means "blank space" or "new line", but I cannot find it.
This is the code I have tried, but it does not work either.
$allimages = preg_replace('/\s\s+/', ' ', $allimages)
Please help.
Below is the php file I am pulling the image names from. There is no code in this file, just text.
a_little_kitten.jpg
black_cat.jpg
basket.jpg

Try rtrim link or trim to remove the whitespace. As I can see that there is a whitespace at the end of your a_little_kitten.jpg and black_cat.jpg file.
&#10 represents a line feed. Maybe you can use str_replace()
ex: str_replace(array("\n", "\r"), '', $photos) before for loop.

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

PHP removing forward slashes when concatenating

I'm making a script to display all images in a specific folder using PHP. However, when iterating through the for loop, my string holding the image destination (../images/uploads/imageName.png) is having the forward slashes removed (so in the actual image tag it looks like: .. images uploads imageName.php). The file destination displays correctly when echoing out the $num string. My script is displayed below:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$files = glob("../images/uploads/*.*");
for ($i = 0; $i < count($files); $i++) {
$num = $files[$i];
echo $num;
echo '<img src"'.$num.'" alt="random image">'." ";
}
Any help would be very much appreciated
Your missing something here:
echo '<img src"'.$num.'" alt="random image">'." ";
Such as the = between src and the value
echo '<img src="'.$num.'" alt="random image">'." ";
I am sure your image won't display without it regardless of what the path was....
forward slashes removed (so in the actual image tag it looks like: .. images uploads imageName.php). The file destination displays correctly when echoing out the $num string.
What your probably seeing is how the browser is breaking when trying to figure out the HTML tag. Because it's correct when you echoing out the $num string the value of the variable is correct, it's the tag that is breaking down. PHP is not just going to magically do something to the value of a variable from one line to the next.
Cheers!
this will add a slash if your link doesn't have any slash at the end
if(substr($yourlinkvariable, -1) !== "/") {
$yourlinkvariable .= "/";
}
Maybe try with str_replace() function like so :
$num = str_replace(' ', '/', $files[$i]);
This should replace spaces by slash

PHP: uploading text file to page, which shows new line for each text entry, and sorted alphabetically

I'm using PHP and I want to upload a text file, with the output / view showing each line from the text file on a new line (so exactly as it is displayed in the text file).
However, I also want the text file to be sorted alphabetically.
I have working code that uploads the file on each new line, and sorts by upper case, then lowercase - using the sort function
And I have code which sorts it alphabetically (regardless of case), but unfortunately the lines are grouped together, and not separated as I want them to be. - using the natcasesort
I've tried numerous things but not getting anywhere, so hoping someone can help either put the two together, or let me know what I need to do to either piece of code which will make each line show on a new line.
1st CODE NEEDS TO BE SORTED ALPHABETICALLY REGARDLESS OF UPPER/LOWERCASE
2nd CODE NEEDS TO SHOW THE LINE BREAKS
<?php
$file = file("users.txt");
sort($file);
for($i=0; $i<count($file); $i++)
{
$states = explode(",", $file[$i]);
echo $states[0], $states[1],"<br />";
}
?>
<?php
$filename="users.txt";
$lines = array();
$file = fopen($filename, "r");
while(!feof($file)) {
$lines[] = fgets($file,4096);
}
natcasesort($lines);
print_r($lines);
fclose ($file);
?>
You must use
$text = implode("<br />", $lines);
echo $text
It would glue the array and pasting a <br /> in every new line. Of course, if it is being printed in HTML, if not use the carrier \n instead.
And your code would look like:
.
.
.
while(!feof($file)) {
$lines[] = fgets($file,4096);
}
natcasesort($lines);
$text = implode("<br />", $lines);
print_r($text)
.
.
.

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

How to stop PHP Domdocument::SaveXML from inserting "CDATA"?

I'm using PHP to get all the "script" tags from web pages, and then appending text after the </script> that is not always valid html. Because it's not always valid markup I can't just use appendchild/replacechild to add that information, unless I'm misunderstanding how replacechild works.
Anyway, when I do
$script_tags = $doc->getElementsByTagName('script');
$l = $script_tags->length;
for ($i = $l - 1; $i > -1; $i--)
$script_tags_string = $doc->saveXML($script_tags->item($i));
This puts "<![CDATA[" and "]]>" around the contents of the script tag. How can I disable this? Please don't tell me to just delete it afterwards, that's what I'm going to do if I can't find a solution for this.
I have a suspicion that the CDATA is inserted because it would otherwise be invalid XML.
Have you tried using saveHTML instead of saveXML?
One way I've found to fix this:
Before echoing the document, make a loop around all script tags, and use str_replace for "<", ">" to some string, make sure to only use that string inside script tags.
Then, use the method saveXML() in a variable, and finally use str_replace replacing "STRING" to "<" or ">"
Here is the code:
<?php
//First loop
foreach($dom->getElementsByTagName('script') as $script){
$script->nodeValue = str_replace("<", "ESCAPE_CHAR_LT", $script->nodeValue);
$script->nodeValue = str_replace(">", "ESCAPE_CHAR_GT", $script->nodeValue);
}
//Obtaining XHTML
$output = $dom->saveXML();
//Seccond replace
$output = str_replace("ESCAPE_CHAR_LT", "<", $output);
$output = str_replace("ESCAPE_CHAR_GT", ">", $output);
//Print document
echo $output;
?>
As you can see, now you are free to use "<" ">" in your scripts.
Hope this helps someone.

Categories