开发者

php replace a pattern

开发者 https://www.devze.com 2022-12-28 00:17 出处:网络
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 t开发者_开发问答ext yourinput and save the file using php

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 t开发者_开发问答ext yourinput and save the file using php

The pattern is *.c

thanks..


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();


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)$/


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消