Log in

View Full Version : deleting a line containing a string (help)



sfchun
04-29-2008, 11:01 AM
Hello

I opened a file in a variable
and I'm searching for the code to delete (or replace with blank) a line
which contain a specific word/string, the rest of the line is generated and can be different each time.

example :
assuming :
- what is generated randomly is in red
- what i search is in green (and it normaly seen only once in the file)

$file = "1031hc023blablabla461hjk0456"

How i can delete this line ?? (from the string and not the file/string).
Is there a simple code line ? or should i count the line as if it was a file ??
Can i use something like : str_replace or preg_replace ??
I couldn't find an example doing this on the web :(

someone help ?

Medyman
04-29-2008, 12:05 PM
I think this is what you're looking for:

str_replace("blablabla", "", $file);

sfchun
04-29-2008, 01:40 PM
if no mistake, this will replace a part of the string, by nothing,
but the rest of the line will stay.

what i need is to delete the the full line once the 'blablabla' had been found

Medyman
04-29-2008, 03:01 PM
Oh, I see now...

The below will do the trick. There are probably other ways do to it. More knowledgable folk might have different recommendations:



<?php

$file = "1031hc023blablabla461hjk0456";
if (substr_count($file, 'blablabla') > 0) {
$file = "";
}

?>


This bascially test to see if 'blablabla' is within the string. If it is, it wipes the variable clean.

sfchun
04-29-2008, 03:17 PM
it's not exactly what i need, cause in fact my $file variable, contains more than only one line ...

if i use this trick it removes not only the line but also the rest of the variable :p

sfchun
04-30-2008, 03:44 AM
I changed my way of reading the file at the beginning (even if it's not what i wanted to do at first...
but i was wrong in a sens ... my variable was containing ONE line (with all the text) only, so i couldn't logically ask PHP to remove a specific line in it -_-;;;

so rather that get the whole file in a $variable
i read the file lines in an array[],
then i use your trick to test the line and replace it by blank if needed...

now it works...