Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Searching and replacing text within a file 2

Status
Not open for further replies.

jahjah

Technical User
Jan 23, 2003
32
GB
Can anyone help I am trying to search for text within a file and replace it with predetermined variables - I have tried egrep_replace but dont seem to be having much luck - does any one have any suggestions?? The text I need to replace are a date (DD/MM/YY) and a letter followed by 4 numbers (M9999)
TIA
JahJah
 
I use this when I need to replace URL address in some text with the link (<a href=URL>URL</a>), it can help you:
Code:
  if(!(($url_pos=strpos($message,&quot;[URL unfurl="true"]http://&quot;))===false[/URL] {  // insert link when &quot;[URL unfurl="true"]http://&quot;[/URL] is found
    $message_length=strlen($message);
    for($i=$url_pos;$i<$message_length;$i++) if(($message[$i]==&quot; &quot;)||($message[$i]==&quot;\r&quot;)||($message[$i]==&quot;\n&quot;)) break;
    $end_pos=$i;
    $url=&quot;&quot;;
    for($i=$url_pos;$i<$end_pos;$i++) $url.=$message[$i];
    $link=&quot;<A href=\&quot;&quot; . $url . &quot;\&quot;>&quot; . $url . &quot;</A>&quot;;
    $message=str_replace($url,$link,$message);
  }

The only bad thing is that it can replace only one URL in the text - I haven't fixed it yet because it is not easy in this case. The &quot; string is present even after replacement and it is not desirable to replace it for the second time. If you replace the string with something different, you will only need to write 'while' instead of 'if' at the begining of the code.
 
sorry, the first line of code should be:
Code:
if(!(($url_pos=strpos($message,&quot;[URL unfurl="true"]http://&quot;))===false))[/URL] {
 
Hello Gizmicek
Unfortunately this doesnt seem to be of much help... I need to open up a file, search for the 2 criteria mentioned above and replace the text with variables.
 
jahjah,

preg_replace should work.
What you are looking for is a date and let's assume it's surrounded by a space before and after.
The regexp would be '/\s\d{2}\/\d{2}\/\d{2}\s/'.
In clear text: find a single space followed by 2 digits, a forward slash (which needs to be escaped) etc.
Code:
$pattern = '/\s\d{2}\/\d{2}\/\d{2}\s/';
# don't forget to pad the replacement
$replace= ' '.$yourVarHere.' ';
$txt = preg_replace($pattern,$replace, $txt);

So, that was easy.
The second pattern is not much different.
'/\b\w\d{4}\s/'
Again, don't forget to pad it when replacing.

This will work on all instances of the patterns described.
 
Thanks DRJ478
that seems to have helped a little - for some reason however I cannot get it to replace the text within the file it deltes the files contents here is a snippet of the script;

@ $fp = fopen(&quot;$FILE&quot;,&quot;w&quot;, 2);

if (!fp)
{
echo &quot;<P><STRONG>Cannot open the file</STRONG></P>&quot;;
exit;
}

$pattern = '/\d{2}\/\d{2}\/\d{2}\s/'; // Only 1 space at end of the date field

$replace= $FULLDATE;

$txt = preg_replace($pattern,$replace, $txt);

fclose($fp);
}
 
What you'll need to do (unless there's a better way), is read the file in line by line, then write the file out to a new temporary file line by line, with your changes. Then delete the first file and copy the temp file to that name.

There may be a way to modify the file on the fly, it's just that I'm not familar with it, if it exists though please share it with us, could be very useful for many people I'm sure.

-Rob
 
Use the file_get_contents() function, which takes the filename as a parameter and returns the whole content of the file. You can store it into the string and work with the string instead of file. As soon as you have replaced the desired substrings, open the file for writing (w) and store the string into the file. The W parameter of fopen means 'open the file for writing and truncate it to the size of 0'.
 
All right.
You are missing some key steps.

fopen() gives you a file handle, not the file content. You have to read the file content into a variable using fread().
Also, you specified w which truncates the file to length zero - that's why nothing is in there.
Use &quot;r+&quot; which is read/write.
Code:
@ $fp = fopen($FILE,&quot;r+&quot;, 2);
# later read the content into a variable
$txt = fread($fp, filesize($FILE));

# now comes the replacement just as described
$pattern = '/\d{2}\/\d{2}\/\d{2}\s/'; // Only 1 space at end of the date field
$replace= $FULLDATE;
$txt = preg_replace($pattern,$replace, $txt);

# next you need to write the changed text to the file
fwrite($fp, $txt);
fclose($fp);
[code]

This is still very crude. There should be error checking and you should probably write to a temporary file, rename the original to a backup name, rename the new one to the original name.
These things later. Start simple, then attempt more eloborate things.
 
>DRJ478
I prefer the file_get_contents() function instead of fread($f,filesize($FILE)) because I had some problems with the filesize, which didn't return the correct filesize and the file hasn't been read whole.
 
>gizmicek
Thanks for the tip. I've never had problems using fread. However, your point seems to be supported by the PHP documentation which states:

file_get_contents() is the preferred way to read the contents of a file into a string.
 
>DRJ478
The thing is that I have made some web forum some time ago and I didn't have any knowledge about databases, so I needed to use simple file, which hold all forum content. The problem was that when someone submited some text, in the begining of the script I wrote the text into the file and later get the whole content when I was writing out all posts of the forum to the page. But the filesize returned me the size of the file valid before I wrote there new post (even when I closed the file and then opened again). So the result was that the new text was written properly but the part of the last text was truncated... I tried to solve this, but with no success, so I used file_get_contents() and everything was OK ;D
 
Thanks Everyone for helping,
DRJ478 I tried you method and after a little changing round using temp files I have a file with the replacement date in, how would you say was the best way of searching and replacing for both of the criteria mentioned without breaking the script??
PS how does the other search ie:'/\b\w\d{4}\s/' work?

Thanks for your help
JahJah
 
The second pattern in clear text:
Code:
\b look for a word boundary
\w one word character (a-zA-Z0-9)
\d{4} four digits
\s one whitespace character

Just execute the preg_replace twice. If you want to be fancy, assign the patterns and the replacements to arrays.
 
I cant seem to get the pattern matching for the 2nd search to work - this is the command I am using which seems to be working fine with the date search/replace.

$pattern2='/\b\w\d{4}\s/'; //search for M9999 at start of line
$replace2=$NEWQTY; //

$txt = preg_replace($pattern2,$replace2, $txt);

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top