tags:

views:

41

answers:

3

Suppose in a file there is a pattern as sumthing.c: and asdfg.c: and many more.. with *.c: pattern

How to replace this with the text yourinput and save the file using php

The pattern is *.c

thanks..

+3  A: 

You can read the contents of the file into a PHP string using file_get_contents, do the *.c to yourinput replacement in the string and write it back to the file using file_put_contents:

$filename = '...'; // name of your input file.
$file = file_get_contents($filename) or die();
$replacement = '...'; // the yourinput thing you mention in the quesion
$file = preg_replace('/\b\w+\.c:/',$replacement,$file);
file_put_contents($file,$filename) or die();
codaddict
'or die' must die
stereofrog
A: 

You can use PHP's str_replace or str_replace ( in case its a regex pattern). CHeck the syntax of these two functions and replace the *.c with your input.

.c pattern should be something like /?(.c)$/

wouldn't it be `/\.c$/` ? (I've never see a ? at the start of a regex before: what's it do?)
nickf
A: 

First open file and get it's content:

$content = file_get_contents($path_to_file);

Than modify the content:

$content = preg_replace('/.*\.c/', 'yourinput');

Finally save the result back to the file.

file_put_contents($path_to_file, $content);

Note: You may consider changing the regexp because this way it match the '.c' string and everything before it. Maybe '/[a-zA-Z]*\.c/' is what you want.

Petr Peller
`/^.*\.c$/` is how you'd match the whole line - don't forget the `$` at the end there, otherwise any file with ".c" in it (eg: myfile.cab, myfile.current.txt) will be matched.
nickf