I'm running into an issue with finding specific text and replacing it with alternative text.
I'm testing my code below with .rtf and .txt files only. I'm also ensuring the files are writable, from within my server.
It's a hit and miss situation, and I'm curious if my code is wrong, or if this is just weirdness of opening and manipulating files.
<?php
$filelocation = '/tmp/demo.txt';
$firstname = 'John';
$lastname = 'Smith';
$output = file_get_contents($filelocation);
$output = str_replace('[[FIRSTNAME]]', $firstname, $output);
$output = str_replace('[[LASTNAME]]', $lastname, $output);
$output = str_replace('[[TODAY]]', date('F j, Y'), $output);
// rewrite file
file_put_contents($filelocation, $output);
?>
So, inside the demo.txt file I have about a full page of text with [[FIRSTNAME]], [[LASTNAME]], and [[TODAY]] scattered around.
It's hit and miss with the find/replace. So far, [[TODAY]] is always replaced correctly, while the names aren't.
Has anyone had this same issue?
(on a side note, I've checked error logs and so far no PHP warning/error is returned from opening the file, nor writing it)
Hard to say for sure without seeing the contents of demo.txt. My first guess is that it might be a problem with using brackets for your pointers. I would try changing to something not used by RTF like percent signs or an asterisk. ex: %%FIRSTNAME%%, **FIRSTNAME** (this is assuming of course that you have control of the contents of demo.txt.)
I have had this issue too. It seems like Microsoft Word inserts formatting codes in the tags. I have made a blog post about how to get around this on my technical blog.
http://tech.humlesite.eu/2017/01/13/using-regular-expression-to-merge-database-content-into-rich-text-format-template-documents/
The PHP example is shown here:
<?php
$file = file_get_contents('mergedoc.rtf');
// To temporary get rid of the escape characters...
$mergetext = str_replace("\\", "€€", $file);
// New seven part regex with default value detection
$regex2 = '/<<((?:€€[a-z0-9]*|\}|\{|\s)*)([a-z0-9.\-\+_æøåÆØÅA-Z]*)((?:€€[a-z0-9]*|\}|\{|\s)*)([a-z0-9.\-\+_æøåÆØÅA-Z]*)((?:€€[a-z0-9]*|\}|\{|\s)*)(?:\s*:(.*?)\s*)?((?:€€[a-z0-9]*|\}|\{|\s)*)>>/';
// Find all the matches in it....
preg_match_all($regex2,$mergetext, $out, PREG_SET_ORDER);
// Lets see the result
var_dump($out);
foreach ($out as $match) {
$whole_tag = $match[0]; // The part we actually replace.
$start = $match[1]; // The start formatting that has been injected in our tag, if any
$tag = $match[2]; // The tag word itself.
if (($match[4].$match[6]) != "") { //some sec-part tag or default value?
$end = $match[5]; // The end formatting that might be inserted.
if ($end == "") {
$end = $match[7]; // No end in 5, we try 7.
}
} else {
$end = $match[3]; // No second tag or default value, we find end in match-3
}
$secPartTag = $match[4]; // Do we have inserted some formatting inside the tag word too ?
if ($secPartTag != "") {
$tag .= $secPartTag; // Put it together with the tag word.
}
$default_value = $match[6];
// Simple selection of what we do with the tag.
switch ($tag) {
case 'COMPANY_NAME':
$txt = "MY MERGE COMPANY EXAMPLE LTD";
break;
case 'SOMEOTHERTAG':
$txt = "SOME OTHER TEXT XX";
break;
case 'THISHASDEFAULT':
$txt = "";
break;
default:
$txt = "NOTAG";
}
if ($txt == "") {
$txt = $default_value;
}
// Create RTF Line breaks in text, if any.
$txt = str_replace(chr(10), chr(10)."\\line", $txt);
// Do the replace in the file.
$mergetext = str_replace($whole_tag, $start.$txt.$end, $mergetext);
}
// Put back the escape characters.
$file = str_replace("€€", "\\", $mergetext);
// Save to file. Extention .doc makes it open in Word by default.
file_put_contents("ResultDoc.doc", $file);
?>
Related
I was trying to get the text starting from css:{(some text...)} up to the ending bracket only, not including the texts below in another text file using php.
test.sample
just a sample text
css:{
"css/test.css",
"css/test2.css"
}
sample:text{
}
I'm using vscode/sublime search and replace tool to test my regex syntax and nothing is wrong, I successfully get the text that I want including all the new lines and spaces inside, but when i tried to apply it on php, the regex that I created doesn't work, it cannot find the text that im looking for.
here is my code:
myphp.php
$file = file_get_contents("src/page/test.sample");
echo $file . "<br>";
if (preg_match_all("/(css\s*\n*:\s*\n*\{\s*\n*)+((.|\n\S)*|(.|\n\s)*)(\n*)(\}\W)$/", $file)) {
echo "Success";
} else {
echo "Failed!";
}
This is my regex that I just created.
(css\s*\n*:\s*\n*{\s*\n*)+((.|\n\S)|(.|\n\s))(\n*)(}\W)$
Please help me, Im open for any suggestion, Im a newbie on regular expression, Im lacking on knowledge about the logic of it.
thanks.
Try this my friend:
<?php
$file = "testfile.php"; // call the file
$f = fopen($file, 'rb'); // open the file
$found = false;
while ($line = fgets($f, 1000)) { // read every line of the file
if ($found) {
echo $line;
continue;
}
if (strpos($line, "css:") !== FALSE) { // if we found the word 'css:' we print everything after that
$found = true;
}
}
Hey guys I found the solution! base on the answer of #alex
Dont really know if I am implementing this right.
Here is my code
$src = "src/page/darwin.al"; //get the source file
$file = fopen($src,"rb"); //I dont really know what 'rb' means, I guess it simply means, 'not a commong text file'?, search for it!
$found = false;
$css = false;
while($line = fgets($file)){ //read every line of text and assign that line of text in a variable $line
if(strpos(preg_replace("/\s*/", "", $line), "css:{") === 0){ //if the current line is == 'css:{' <the thing that Im looking for,
$found = true;
$css = true;
}elseif($css && strpos(preg_replace("/\s*/", "", $line),"}") === 0){ //If we are still inside the css block and found the '{'
echo $line;
break;
}
if ($found) {
echo preg_replace("/\s*/", "", $line); //remove every whitespace!
}
}
fclose($file);//close the file
i searched Google but found nothing what fits for my problem, or i search with the wrong words.
In many threads i read, the smarty Template was the solution, but i dont wont use smarty because its to big for this little project.
My problem:
I got a CSV file, this file contents only HTML and PHP code, its a simple html template document the phpcode i use for generating dynamic imagelinks for example.
I want to read in this file (that works) but how can i handle the phpcode inside this file, because the phpcode shown up as they are. All variables i use in the CSV file still works and right.
Short Version
how to handle, print or echo phpcode in a CSV file.
thanks a lot,
and sorry for my Bad english
Formatting your comment above you have the following code:
$userdatei = fopen("selltemplate/template.txt","r");
while(!feof($userdatei)) {
$zeile = fgets($userdatei);
echo $zeile;
}
fclose($userdatei);
// so i read in the csv file and the content of csv file one line:
// src="<?php echo $bild1; ?>" ></a>
This is assuming $bild1 is defined somewhere else, but try using these functions in your while loop to parse and output your html/php:
$userdatei = fopen("selltemplate/template.txt","r");
while(!feof($userdatei)) {
$zeile = fgets($userdatei);
outputResults($zeile);
}
fclose($userdatei);
//-- $delims contains the delimiters for your $string. For example, you could use <?php and ?> instead of <?php and ?>
function parseString($string, $delims) {
$result = array();
//-- init delimiter vars
if (empty($delims)) {
$delims = array('<?php', '?>');
}
$start = $delims[0];
$end = $delims[1];
//-- where our delimiters start/end
$php_start = strpos($string, $start);
$php_end = strpos($string, $end) + strlen($end);
//-- where our php CODE starts/ends
$php_code_start = $php_start + strlen($start);
$php_code_end = strpos($string, $end);
//-- the non-php content before/after the php delimiters
$pre = substr($string, 0, $php_start);
$post = substr($string, $php_end);
$code_end = $php_code_end - $php_code_start;
$code = substr($string, $php_code_start, $code_end);
$result['pre'] = $pre;
$result['post'] = $post;
$result['code'] = $code;
return $result;
}
function outputResults($string) {
$result = parseString($string);
print $result['pre'];
eval($result['code']);
print $result['post'];
}
Having PHP code inside a CSV file that should be parsed and probably executed using eval sounds pretty dangerous to me.
If I get you right you just want to have dynamic parameters in your CSV file right? If thats the case and you don't want to implement an entire templating language ( like Mustache, Twig or Smarty ) into your application you could do a simple search and replace thing.
$string = "<img alt='{{myImageAlt}}' src='{{myImage}}' />";
$parameters = [
'myImageAlt' => 'company logo',
'myImage' => 'assets/images/logo.png'
];
foreach( $parameters as $key => $value )
{
$string = str_replace( '{{'.$key.'}}', $value, $string );
}
First excuse me for the bad english.
I am trying to build a php script to search multiple webpages from a .txt file for specific word.
More specific:
I have a .txt file where i have stored many urls (every url is on one line, so if i have 10 urls the file have 10 lines) and i want the script to check the webpage content of each url for a specific word. So if the word is found on the webpage the script will return ONLINE othewise will return DOWN.
I build the script but the problem is that it always return ONLINE even if the url from file doesn't have the specific word in it's webpage content.
<?php
$allads = file("phpelist.txt");
print("Checking urls: <br><br><br><strong>");
for($index = 0; $index <count($allads); $index++)
{
$allads[$index] = ereg_replace("\n", "", $allads[$index]);
$data = file_get_contents('$allads[$index]');
$regex = '/save/';
if (preg_match($regex, $data)) {
echo "$allads[$index]</strong>...ONLINE<br><strong>";
} else {
echo "$allads[$index]</strong>...DOWN<br><strong>";
}
}
print("</strong><br><br><br>I verified all urls from file!");
?
To search the particular webpage for a given string, I'd use stripos() (case-insensitive) or strpos() (case-sensitive) instead of regular expressions:
if( stripos(haystack, needle) !== FALSE ) {
//the webpage contains the word
}
An example:
$str = 'sky is blue';
$wordToSearchFor = 'sky';
if (strpos($str, $wordToSearchFor) !== false) {
echo 'true';
}
else {
echo 'Uh oh.';
}
Demo!
Although, programmitcally skimming through webpages isn't considered a good practice and shouldn't be done unless it's absolutely necessary.
UPDATE:
In your file_get_contents call you're doing:
$data = file_get_contents('$allads[$index]');
You're using single quotes, and the variable values do not get replaced. You'll have to use double quotes to have file_get_contents fetch the actual URL. Replace it with:
$data = file_get_contents("$allads[$index]");
Another thing I noticed is that you're using the deprecated ereg_replace() function in your code. See the red box? Relying on depreacted functions are highly discouraged.
Your code, after all the above corrections, should look like:
$allads = file("phpelist.txt");
print("Checking urls: <br><br><br><strong>");
for($index = 0; $index <count($allads); $index++)
{
$allads[$index] = str_replace("\n", "", $allads[$index]);
$data = file_get_contents("$allads[$index]");
$searchTerm = 'the';
if (stripos($data, $searchTerm) !== false) {
echo "$allads[$index]</strong>...ONLINE<br><strong>";
}
else
{
echo "$allads[$index]</strong>...DOWN<br><strong>";
}
}
print("</strong><br><br><br>I verified all urls from file!");
?>
Okay so I have a text file and inside of the text file I have these lines:
IP = 127.0.0.1
EXE = Client.exe
PORT = 8080
TITLE = Title
MAINT = False
MAINT-Message = This is the message.
what I am wanted to do is get the 'False' part on the fifth line.
I have the basic concept but I can't seem to make it work. This is what I have tried:
<?php
$file = file_get_contents('LauncherInfo.txt');
$info = explode(' = ', $file);
echo $info[5];
?>
And with this I get a result but when I echo $info[5] it gives me 'False Maint-Message' so it splits it but it only splits at the = sign. I want to be able to make it split at the where I have pressed enter to go onto the next line. Is this possible and how can I do it?
I was thinking it would work if I make it explode on line one and then do the same for the second line with a loop until it came to the end of the file? I don't know how to do this though.
Thanks.
I think you're looking for the file(), which splits a file's contents into an array of the file's lines.
Try this:
$file = file('LauncherInfo.txt');
foreach ($file as $line) {
if ($line) {
$splitLine = explode(' = ',$line);
$data[$splitLine[0]] = $splitLine[1];
}
}
echo $data['MAINT'];
Just in case you were curious, since I wasn't aware of the file() function. You could do it manually like this
<?php
$file = file_get_contents('LauncherInfo.txt');
$lines = explode("\n", $file);
$info=array();
foreach($lines as $line){
$split=explode(' = ',$line);
$info[]=$splitline[1];
}
echo $info[5];//prints False
?>
I am writing an email module for my web app that sends a html email to a user on completion of a task such as signing up. Now as the formatting of this email may change I've decided to have a template html page that is the email, with custom tags in it that need to be replaced such as %fullname%.
My function has an array in the format of array(%fullname% => 'Joe Bloggs'); with the key as the tag identifier and the value of what needs to replace it.
I've tried the following:
$fp = #fopen('email.html', 'r');
if($fp)
{
while(!feof($fp)){
$line = fgets($fp);
foreach($data as $value){
echo $value;
$repstr = str_replace(key($data), $value, $line);
}
$content .= $repstr;
}
fclose($fp);
}
Is this the best way to do this? as only 1 tag get replaced at the moment... am I on the right path or miles off??
thanks...
I think the problem is in your foreach. This should fix it:
foreach($data as $key => $value){
$repstr = str_replace($key, $value, $line);
}
Alternatively, I think this should be more effective:
$file = #file_get_contents("email.html");
if($file) {
$file = str_replace(array_keys($data), array_values($data), $file);
print $file;
}
//read the entire string
$str=implode("\n",file('somefile.txt'));
$fp=fopen('somefile.txt','w');
//replace something in the file string - this is a VERY simple example
$str=str_replace('Yankees','Cardinals',$str);
//now, TOTALLY rewrite the file
fwrite($fp,$str,strlen($str));
That looks like it should work, but I'd use "file_get_contents()" and do it in one big blast.
A slightly different approach is to use PHP's heredocs combined with string interpolation i.e.:
$email = <<<EOD
<HTML><BODY>
Hi $fullname,
You have just signed up.
</BODY></HTML>
EOD;
This avoids a separate file, and should make things beyond simple substitution easier later.