Replace path and quotes with new url in file - php

I have a text file with the following data:
"K:\data\etrdtCfhbr6MUkAAFuVw.jpg"
"K:\data\rgtdrCfhbr6OUYAE5lNR.jpg"
"K:\data\Cfhbr6VVIrdtdAAmRPr.jpg"
"K:\data\Cffh-EyWsersetsAQ8eIz.jpg"
I want to replace the quotes and part of the path to get an output like this:
http://myweb.com/dat/etrdtCfhbr6MUkAAFuVw.jpg
http://myweb.com/dat/rgtdrCfhbr6OUYAE5lNR.jpg
http://myweb.com/dat/Cfhbr6VVIrdtdAAmRPr.jpg
http://myweb.com/dat/Cffh-EyWsersetsAQ8eIz.jpg
Right now I have some (pseudo)code where I don't know how to get it working correctly:
$filecontents = file_get_contents('/path/to/file.txt'); //Load the file contents
$newcontent = preg_replace('.....', $filecontents); //Use a regex to replace the stuff as I want
file_put_contents('/path/to/file.txt', $newcontent);
I highlighted the code where I'm stuck right now.

You can get your file as a string with file_get_contents(). Then you can use preg_replace() to replace each path as you want. And with file_put_contents() you simply save the file back.
The regex /\".*\\\\(.*?)\"/m simply means:
\".*\\\\ match a double quote(\") and then everything(.*) until the last backslash(\\\\)
(.*?)\" match everything((.*?)) until a double quote(\")
m modifier m simply means to use the regex for each line
Code
<?php
$file = file_get_contents("test.txt");
$file = preg_replace("/\".*\\\\(.*?)\"/m", "http://myweb.com/dat/$1", $file);
file_put_contents("test.txt", $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 use a function inside a variable?

What I'm trying to do here is make use of PHP's ability to create and write to files because I have like 350 pages to make all with the same line of code that differs by one number. Much rather do this through code than manually creating 350 pages!
Each file will be (.php) and named after the title of the content it will have which has already been defined. However, as this will be the URL to reach the page, I need to format the title and use the formatted version as the filename.
This is what I've got to start with:
function seoUrl($string) {
//Make lowercase
$string = strtolower($string);
//Clean up multiple dashes or whitespaces
$string = preg_replace("/[\s-]+/", " ", $string);
//Convert whitespaces and underscore to dash
$string = preg_replace("/[\s_]/", "-", $string);
return $string;
}
I found this function earlier on here and it worked perfectly for making the sitemap for all these pages. The URLs were just like I wanted. However, when I call the same function to do this for each title, I hit a snag. I assume I have the code wrong somewhere so here's a piece of the file creation code:
//Content title to be formatted for the filename
$title1="Capitalized And Spaced Title";
//Formatting
$urlfile1="seoUrl ($title1)";
//Text to be written
$txt1="<?include 'tpl/pages/1.txt'?>";
//And the create/write file code
$createfile1=fopen("$urlfile1.php", "w");
fwrite($createfile1, $txt1);
fclose($createfile1);
The code inserts the $txt values just fine, which is actually where I anticipated having a problem. But my files that are created include the function name and parenthesis, plus the title isn't formatted.
I didn't have this problem on the sitemap page:
$url1="$domainurl/$pathurl/$title1.php";
$url2="$domainurl/$pathurl/$title2.php";
...
seoUrl($url1);
seoUrl($url2);
...
<?echo $url1?><br>
<?echo $url2?><br>
...
I've tried everything I can think of for the past couple hours now. What am I doing wrong here?
Try this i hope this might help you out. it will create file in proper format.
function seoUrl($string) {
//Make lowercase
$string = strtolower($string);
//Clean up multiple dashes or whitespaces
$string = preg_replace("/[\s-]+/", " ", $string);
//Convert whitespaces and underscore to dash
$string = preg_replace("/[\s_]/", "-", $string);
return $string;
}
$title1 = "Capitalized And Spaced Title";
//Formatting
$urlfile1 = seoUrl($title1);
//Text to be written
$txt1 = "<?include 'tpl/pages/1.txt'?>";
//And the create/write file code
$fileName = "" . $urlfile1 . ".php";
$createfile1 = fopen($fileName, "w");
fwrite($createfile1, $txt1);
fclose($createfile1);

PHP & HTML <a href> leaving extra space?

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.

file_get_contents() skipping text between <> tag

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.

In PHP when using fgets() to read from file how to exclude "brake row"

I'm writing simple function witch will read data from myfile.txt with fgets().
Content of file is something like:
1
2
3
4
Function to get first value (1):
$f = fopen ("myfile.txt", "r");
$mystring = fgets ($f);
Now, when I use $mystring to write in file like:
$f1 = fopen ("myfile2.txt", "w");
fwrite($f1, 'text' . $mystrin . 'more text');
text 'more text' goes to new row.
I want to have it in in same row with other text.
When reading a file using fgets() it will include the newline at the end. You only need to remove it.
$mystring = trim ($mystring);
This will remove any leading and trailing whitespaces.
$mystring = rtrim ($mystring, PHP_EOL);
Will remove any trailing newlines.

Categories