I have string with x occurrences of some substring. I need replace every occurrences of substring one by one (not all at one step) and everytime when I replace one substring, i need save this substring into variable before it will be replaced...
Exactly - I have input with text and three images in base64. I need cut base64 code of images (replace it with '') and save this img base64 code into new file and echo only input text without base64 code of imgs...
I tried for loops, while loops, functions... but everytime it replace only first occurrences of substring and not other
I think that I must save $original_string every time in loop cycle, because in my codes it always start with whole $original_string from input. But I don't know how I must do it...
$img_count = substr_count($original_string, "data:image");
for ($i = 0; $i < $img_count; $i++) {
$img_name = get_string_between($original_string, 'data-filename="', '.');
$img_base64 = get_string_between($original_string, 'src="', '"');
$original_string = str_replace($img_base64, '', $original_string);
$myfile = fopen("../img/clanky/" . $id_noveho_clanku . "/" . $img_name . ".txt", "w") or die("Unable to open file!");
$txt = $img_base64;
fwrite($myfile, $txt);
fclose($myfile);
}
while (strpos($original_string, "data:image") !== false) {
$img_name = get_string_between($original_string, 'data-filename="', '.');
$img_base64 = get_string_between($original_string, 'src="', '"');
$original_string = str_replace($img_base64, '', $original_string);
$myfile = fopen("../img/clanky/" . $id_noveho_clanku . "/" . $img_name . ".txt", "w") or die("Unable to open file!");
$txt = $img_base64;
fwrite($myfile, $txt);
fclose($myfile);
}
I want to have 3 files with base64 code of images and twxt from input without this base64. But I have only one file, and text without only first occurrence.
EDIT:
so, I find out this...
I upload img "výstřižek.jpg", On my web img are render correctly, without errors. if I see on my admin site on webhosting, I see this name correctly in files, but if I connect to my host server by filezilla FTP and I open file tree in this FTP client, there I see "VýstÃÂiþek3.jpg". But why??
I cant post images here, so I upload screenshots on gdrive, please view them, for better understood of actual problem
https://drive.google.com/open?id=1OQn-L1xePo6o1I6U7mmvZbxiEOBhPLvp
Yes, your code always returns the first result because it's always matching from the beginning of the string, you should remove the part you've already processed for it to work or use an offset from which to start the search in each iterarion: start with 0 and before removing the data, use its position as the next offset. You would then have to pass it to your get_string_between function to limit the search.
But since your original string is in fact html, I'd recommend using some html parsing library to avoid headaches with attributes being on a different order, possible escaping issues, etc. This solution uses the DOM extension that should be enabled by default.
$doc = new DOMDocument();
// Treat the string as a frament and do not add a DOCTYPE or mandatory tags
$doc->loadHTML(mb_convert_encoding($original_string, 'HTML-ENTITIES', 'UTF-8'), LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED);
// Get all images
$imgs = $doc->getElementsByTagName('img');
foreach ($imgs as $img) {
$src = $img->getAttribute('src');
$name = $img->getAttribute('data-filename');
// Check if it contains base64 data and a filename
if (false !== mb_strpos($src, 'data:image') && "" !== $name) {
$data = mb_substr($src, strpos($src, ',') + 1); // Data start
$img->setAttribute('src', mb_str_replace($data, '', $src)); // Remove data
$name = mb_substr($name, 0, strrpos($name, '.'));
// Save the image to disk
$path = "../img/clanky/${id_noveho_clanku}/${name}.txt";
file_put_contents($path, $data);
}
}
// Get the HTML with the data removed
$parsed = $doc->saveHTML($doc);
Demo on 3v4l.org
Related
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
I am trying to read a .tsv file using PHP. I am using the simplest method of file_get_contents() but it is skipping any text between <> tags.
Following is the format of my .tsv file
<id_svyx35_88c_avbfa5> <Kuldeep_Raval> rdf:type <wikicat_Delhi_Daredevils_cricketers>
Following is the code I am using
$filename = "access_s.tsv";
$content = file_get_contents($filename);
//Split file into lines
$lines = explode("\n", $content);
echo $content;
On reading it, the output is just
rdf:type
Please help in what can be the solution to read the line as it is?
Try to apply htmlspecialchars() to $content:
$filename = "access_s.tsv";
$content = htmlspecialchars(file_get_contents($filename));
//Split file into lines
$lines = explode("\n", $content);
echo $content;
Reference on php.net
The tags have always been there, the browser just does not show them. Just like with any valid HTML tag, you can see them when viewing the source code of the website.
I need to add itens from a text file, into a MySQL database, to do that i'm trying to use PHP to read the file and insert everything into the database, the problem is that the text file, has 2 itens per line, divided by spaces, something like this:
teste.txt
ITEM1 ITEM2
ITEM323 ITEM4
ITEM54 ITEM6
ITEM34234 ITEM8
I'm trying to remove the spaces using explode, but because the number of spaces, is random, i cannot do that. This is my Code:
$handle = #fopen("teste.txt", "r"); //read line one by one
while (!feof($handle)) // Loop til end of file.
{
$buffer = fgets($handle, 4096); // Read a line.
list($a,$b)=explode(" ",$buffer);//Separate string by Spaces
//values.=($a,$b);// save values and use insert query at last or
echo $a;
echo "<br>";
echo $b . "<br>"; // NEVER echoes anything
}
What should i do?
You can insert a method to change multiple spaces to one:
$buffer = preg_replace('/\s+/',' ',$buffer);
Right before exploding it:
$buffer = fgets($handle, 4096); // Read a line.
$buffer = preg_replace('/\s+/',' ',$buffer);
list($a,$b)=explode(" ",$buffer);//Separate string by Spaces
You can use preg_replace() to perform a regular expression:
$buffer = preg_replace("/\ +/", " ", fgets($handle, 4096));
I'm reading content from a text file which I'm showing on a page later, this is my code:
$lines = file("content.txt");
$i=1;
foreach($lines as $line ){
$var["line" . $i] = $line;
$i++;
}
extract($var);
The text file includes content in this format:
bla1
bla2
and so on, there's no space behind the domains just a linebreak, now I want to concatenate the content and show it, so I do this:
$as1 = $line1.$line2;
echo $as1;
But instead of the expected result
Bla1Bla2
I get
Bla1 Bla2
What am I doing wrong ? I can assure that there's no space in the text file not behind nor infront of the content.
There's no space; but unless you tell the file() function otherwise, there is a line feed at the end of each line
$lines = file("content.txt", FILE_IGNORE_NEW_LINES);
A browser will render a line feed as a space, unless inside a or block
use trim for this situation
$as1 = trim($line1).trim($line2);
echo $as1;
You could try trimming your input...
$lines = file("content.txt");
$i=1;
foreach($lines as $line ){
$var["line" . $i] = trim($line);
$i++;
}
extract($var);
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)
.
.
.