How to replace PHP code in a file having newlinse - php

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

Related

How do you remove the new line code ( ) with 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.

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.

How can I get file content between two HTML comments and replace it with content from another file?

This is my second time (in a long time) ever touching php. I am trying to replace the file content between two HTML comments with content from another file located in the same directory.
Right now, I am testing by only replacing the content between two HTML comments with a single line ($newCode).
When I run the following code, however, it wants to replace the entire file with nothing but that $newCode line on each line:
#!/bin/php
<?php
// Testing preg_replace() with string
$tagBegin = '<!-- test4 Begin ColdFusion Template Html_Head -->';
$tagEnd = '<!-- test4 End ColdFusion Template Html_Head -->';
$tagSearch = '/[^'. $tagBegin .'](.*)[^'. $tagEnd .']/';
$strReplace = 'Testing php code';
$testString = '<!-- test4 Begin ColdFusion Template Html_Head -->I should be gone.<!-- test4 End ColdFusion Template Html_Head -->';
// Replaces everything between the two tags with the cfReplace code - THIS WORKS
// echo "Testing string replace...";
// echo preg_replace( $tagSearch, $strRieplace, $testString );
// echo ( "\r\n" .$testString );
// Testing replace on ./testAaron.htm - THIS DOES NOT WORK
echo "\r\n Testing file replace...";
$testFile = 'testAaron.htm';
$newCode = 'Replaced <html> and all Header info!!!'; // to be replaced with cf code
echo preg_replace( $tagSearch, $newCode, file_get_contents( $testFile ) );
?>
I have a feeling it's the file_get_contents() in the last parameter of the preg_replace() function, but I don't know why.
When I took out the file_get_contents() and placed only the $testFile in it, the script ran with only one line and none of the rest of the testAaron.htm code.
When I opened the testAaron.htm file, there were no changes at all.
I thought maybe 'echo' was just letting me preview and print what would be changed, so I took that out, but it made no difference.
Your RegEx is definitely incorrect. Look what it evaluates to:
/[^<!-- test4 Begin ColdFusion Template Html_Head -->](.*)[^<!-- test4 End ColdFusion Template Html_Head -->]/
This is wrong; brackets in RegEx denote a character set, not a literal string. Furthermore, adding the caret ^ symbol negates the character set, meaning essentially "none of these characters".
If you want to search for a literal, just use those characters:
$tagSearch = '/'. $tagBegin .'(.*)'. $tagEnd .'/';
Also, I would make the wildcard lazy by adding a ? so it doesn't potentially match other tags in your code:
$tagSearch = '/'. $tagBegin .'(.*?)'. $tagEnd .'/';
Finally, it sounds like you're trying to actually modify the file itself. To do that, you'll need to write your modified data back to the file. Changing the data in-memory will not automatically save those changes to the file on disk.
try this function
echo replace_between($tagSearch, $tagBegin, $tagEnd, file_get_contents( $testFile ));
function replace_between($str, $needle_start, $needle_end, $replacement) {
$pos = strpos($str, $needle_start);
$start = $pos === false ? 0 : $pos + strlen($needle_start);
$pos = strpos($str, $needle_end, $start);
$end = $pos === false ? strlen($str) : $pos;
return substr_replace($str, $replacement, $start, $end - $start);
}

How to add new line in php echo

The text of story content in my database is:
I want to add\r\nnew line
(no quote)
When I use:
echo nl2br($story->getStoryContent());
to replace the \r\n with br, it doesn't work. The browser still display \r\n. When I view source, the \r\n is still there and br is nowhere to be found also. This is weird because when I test the function nl2br with simple code like:
echo nl2br("Welcome\r\nThis is my HTML document");
it does work. Would you please tell me why it didn't work? Thank you so much.
The following snippet uses a technique that you may like better, as follows:
<?php
$example = "\n\rSome Kind\r of \nText\n\n";
$replace = array("\r\n", "\n\r", "\r", "\n");
$subs = array("","","","");
$text = str_replace($replace, $subs, $example );
var_dump($text); // "Some Kind of Text"
Live demo here
I doubt that you need "\n\r" but I left it in just in case you feel it is really necessary.
This works by having an array of line termination strings to be replaced with an empty string in each case.
I found the answer is pretty simple. I simply use
$text = $this->storyContent;
$text = str_replace("\\r\\n","<br>",$text);
$text = str_replace("\\n\\r","<br>",$text);
$text = str_replace("\\r","<br>",$text);
$text = str_replace("\\n","<br>",$text);

Categories