Replace a whole line where a particular word is found in a text file

One approach that you can use on smaller files that can fit into your memory twice: $data = file(‘myfile’); // reads an array of lines function replace_a_line($data) { if (stristr($data, ‘certain word’)) { return “replacement line!\n”; } return $data; } $data = array_map(‘replace_a_line’, $data); file_put_contents(‘myfile’, $data); A quick note, PHP > 5.3.0 supports lambda functions … Read more

Replace None value in list?

Use a simple list comprehension: [‘None’ if v is None else v for v in d] Demo: >>> d = [1,’q’,’3′, None, ‘temp’] >>> [‘None’ if v is None else v for v in d] [1, ‘q’, ‘3’, ‘None’, ‘temp’] Note the is None test to match the None singleton.

Replace string in text file using PHP

Does this work: $msgid = $_GET[‘msgid’]; $oldMessage=””; $deletedFormat=””; //read the entire string $str=file_get_contents(‘msghistory.txt’); //replace something in the file string – this is a VERY simple example $str=str_replace($oldMessage, $deletedFormat,$str); //write the entire string file_put_contents(‘msghistory.txt’, $str);

Replace special characters in a string in Python

One way is to use re.sub, that’s my preferred way. import re my_str = “hey th~!ere” my_new_string = re.sub(‘[^a-zA-Z0-9 \n\.]’, ”, my_str) print my_new_string Output: hey there Another way is to use re.escape: import string import re my_str = “hey th~!ere” chars = re.escape(string.punctuation) print re.sub(‘[‘+chars+’]’, ”,my_str) Output: hey there Just a small tip about … Read more