I have the following string in a text file:
<!--
///////////////////////////////////////////////////////////////////////////////////////
//
// Individuals
//
///////////////////////////////////////////////////////////////////////////////////////
-->
I need to write text two lines below the above part. There are many other sections like the one above, but each one doesn't repeat, so I know there is only one "Individuals".
I need to overwrite the file, so how can I set the position of my output to there?
There are two approaches:
Read the file line by line. Check each line if it matches to certain conditions. If yes, insert lines.
Read the full file, replace the text wanted and write the full file.
As long as your traffic is not too high, method 2 will be simpler. In order to replace the full block, I suggest this regex:
/(<!--[\s\r\n/]*Individuals[\s/]*)[^\s/]*([\s/]*-->)/
It matches the full block containing "Individuals" followed by some content on the new line. The block before the separate content is being caught by parenthesis, in order to do a replace:
$content = file_get_contents('myfile.txt');
$newContent = preg_replace("#(<!--[\s\r\n/]*Individuals[\s/]*)[^\s/]*([\s/]*-->)#", "$1$myNames$2", $content);
file_put_contents('myfile.txt', $newContent);
The preg_replace concatenates the first part of the block, some slashes and "Individuals", together with $myNames, and together with the closing part of the block to a new block.
I have not tested this finally in the shell, so I apologize for a possible typo. But I'm sure this will work out.
Related
Here is the line of code from a PHP file, specifically it is from zstore.php which is a file include as part of the "Zazzle Store Builder" toolset from Zazzle.com
The set of files allows someone like me, who has products for sale on Zazzle and massage that data into a nicer "storefront" which I can set up my way instead of being confined by the CMS structure of Zazzle.com where they understandably want to keep the monkeys (uhmmm... users like myself) from causing too much mayhem.
So... here is the code:
$keywords = str_replace(" ",",",str_replace(",","",$keywords));
Two questions:
Am I understanding what it does and
Is there an extra single or double quote in the string that does not need to be there?
Here is what I think the line of code is saying:
Take the string of characters that the user inputs (dance diva) and assign it to the variable called
$keywords
then run the following function on that character string
= str_replace
(" ","," <<< look for spaces. If you find a space, replace it with a comma
,str_replace(",","" <<< this is the bit I don't understand or which may have a typo
I THINK that it is saying " if you find commas, leave them alone, but I'm not certain.
,$keywords)); <<< then put the edited string of characters backing to the variable called $keywords.
What lead me to look at this was that I was inputting the following:
dance,diva which is what I THOUGHT the script was wanting from me based on the commented text in the README.txt file:
// Search terms. Comma separated keywords you can use to select products for your store
So..
Am I understanding what this line of code is supposed to do?
which, assuming I am correct, and I'm pretty sure that the first half is supposed to work as I've described, now brings me to my second question:
Why isn't the second bit working? Is there a typo?
To review:
dance diva produces results
dance,diva does not
Both, SHOULD work.
Thanks in advance for your help. I have a lot of HTML experience and computer experience but PHP is new to me.
$keywords = str_replace(" ",",",str_replace(",","",$keywords));
You can split into
$temp = str_replace(",","",$keywords);
$keywords = str_replace(" ",",",$temp);
First it replaces all comas with empty string, it is removes all comas. Then replaces all spaces with comas.
For "dance diva" there are no comas so first does nothing, then it replaces space and result is "dance,diva"
For "dance,diva" it removes coma, you get "dancediva" and there in no space to replace next so it is Your result.
Whilst being aware of the pitfalls/dangers of certain html manipulation with regex (instead of using say the PHP dom manipulator) I'm trying to achieve something that should be pretty simple and not that risky.
Basically I have some uncleaned html copy from a database that doesn't use paragraphs but line break tags to produce the effects of paragraphs. Sometimes though the user only entered content with a single break so that the text line returns but without a blank line appearing. In such instances and ONLY in such instances I want to replace that single <br> with two (<br><br>).
So as an example...
This is <br>a test<br><br>example!
would become
This is <br><br>a test<br><br>example!
Note how the second set of breaks is left alone as its already got 2 tags.
Simply replace one or more occurences of <br> with <br> :)
Replace what:
(<br>)+
Replace with:
<br><br>
You can use negative lookahead and lookbehind to solve this:
(?<!<br>)<br>(?!<br>)
See the example here: http://rubular.com/r/WYjoenH1SA
(?<!NOPREFIX)
(?!NOPOSTFIX)
The first part prevents from matching, if the NOPREFIX is present - the second one if NOPOSTFIX is present.
I have a text file of approximately 25,000 lines. About 525kb.
Some lines have random text at the beginning.
Some have long strings of semicolons.
Some others only have three semi-colons and then a space and optionally more text on the same line. These are the lines I want to remove.
Here is a sample....
;;; Updated Time 20120706122706
;;; Generic DEveloper Output
;;; Some Random Comments
;;; I got some more...
;;; Yet another uneeded line
;;; Thanks for using StackOverflow <http://stackoverflow.com>, or...
;;; Not.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Banana Production
[Data_Release_Version]
Version=12586
Released=20120706122706
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Baseline Properties
[BaseLineProperties]
Comment=BaselineProperties
----- and so on.
Once it gets to the first line with 4 or more ; on the line, I need the rest of the file as there are no ";;; " lines.
Trying to find something fast instead of reading everything line and writing it back out if it doesn't match ";;; ".
File is ASCII (possibly UTF-8) text type file.
Any ideas?
Thank you for your time, assistance and knowledge.
What I would suggest is to use file_get_contents() and save file's contents in a variable as a string, then use explode() that string at every newline character, then in a foreach loop, use preg_match() to check if the line begins with 3 semicolons and a space, if it dosent, put it in another array named $output. After foreach, implode() $output and add a newline character and use file_put_contents() to print it in another file. Hope this helps :-)
code:
<?php
$string = file_get_contents($filename);
$array = explode("\n",$string);
foreach($array as $arr) {
if(!(preg_match("^;;;\s",$arr))) {
$output[] = $arr;
}
}
$out = implode("\n",$output);
file_put_contents($path,$out);
?>
Depends.. I would try to load into a string, then do a explode() with newline, so it's in array, then run a foreach with a skip on any that doesnt have strpos == 0 -AND- strpos !== false, you can put in a continue to skip to the next line if it doesnt match.
Another option, is to parse, and skip, or even using fseek, and such. Depends on alot of different factors to determine whats going to be fastest.
You can implode later on, and add the newlines back in, and then push out a file, and/or use line breaks. Depending where the output is supposed to go.
I think you gave the answer yourself:
Make a script that reads the input file line by line in a loop (while). It writes every line into an output file if two conditions are met: 1. a flag ("done") is FALSE and 2. the line does NOT start with ";;; " (not the blank). This removes those lines starting with three semicolons. Once you come about a line containing more semicolons you set the flag to TRUE, thus the remaining lines wil be copied without being examined.
I have a .txt file with content(see first image) I need the content in such a way that It should be numbered and comma at the end of every line(see second image).
I want to insert say: "1"=>" in front of the first line. The numbering will increase on the second line so having about 4747 lines the last number will be 4747.
then insert: ", at the end of every line.
I have some knowlege in PHP so if somebody has solution or idea that will be helpful. I have been formatting this manually and that is very time consuming
Using PHP:
open your original file (consider fopen() or file_get_contents)
Split into an array by newline (explode())
process array line by line (for or foreach)
prepend the current line number
append quote and comma
loop to next array member
When finished - save content to file (file_put_contents())
That should be enough for you to work it out for yourself!
Use PHP's file(), which will give you an array with one element for each line. After that it should be a simple matter of iterating over the array with foreach and concatenating the appropriate bits onto the string. Then use fopen() and fwrite() to write the edited lines to your output file.
I am writing a PHP program which reads file with file_get_contents then attempts to count effective lines in that source file. It must not count empty lines or lines containing comments only. Sample file:
<?php
/**
* blah blah
*/
class Test {
// testfunc
function testfunc(){
return;
}
}
The number of lines in such a file should be 5. Here is what I've got so far:
$f=file_get_contents($this->file);
$f=preg_replace('|/\*.*?\*/|s','',$f);
$f=preg_replace('/^\s*$/','',$f); // <-- does not work
$f=preg_replace("/\n\n*/s","\n",$f);
$count=count(explode("\n",$f));
But for some reason it does not eliminate white-spaces. Is there a better way to get this done?
The following code does the job, since I don't care much about the spaces, but I still wonder, why my original line labeled "does not work" is not removing spaces from empty lines. Is there some extra character at the end? File format is unix.
$f=preg_replace('/ */','',$f); // removes all spaces properly.
Change /^[\s\t]*$/ to be /^\s*$/ms and that should fix it.
The \s class includes tabs, so no need to add \t. The s makes it match newline characters and the m option makes ^ and $ work when data contains multiple lines (matches line breaks).
Also, it might be better to change /\n\n/s to be /[\r\n]{2,}/.
I would just use trim() and then test each line.
foreach ($lines as $line) {
if (strlen(trim($line)) > 0) {
$total++;
}
}
Then, you're set up to test for other conditions as well, such as comment lines and what not. I suspect that this will be faster than doing a find/replace on a potentially large document, but you should test it either way, and choose the fastest method.