preg_replace issue
I would like to put a text instead of the string VERSION=20101203, my problem is only the first field of preg_replace, I am new to regular expresions. I don't know exactly how to tell preg_replace to see that I need to change the string VERSION=20101203
for other text.
So the string has the format:VERSION=YEARMONTHDAY
I was trying with:
$new_content = preg_replace('/^VERSION\=[0-9]{8}/', $replacement, $content);
Where:
$replacement is the new string I want to have $content is the content of a file that it doesn't matter here
I beleive it's not too difficult. Any questions y开发者_开发知识库ou may have with this issue please ask me and I will answer quickly
Thank you very much in advance
^
is anchoring the regular expression to only the beginning of the line. I assume that's part of the problem.
$new_content = preg_replace('/VERSION\=[0-9]{8}/', $replacement, $content);
In addition, you will want to ensure that $replacement
contains the full string for replacing the string matched by VERSION\=[0-9]{8}
.
Try this code (without ^
at the start of regular expression):
$content='foo VERSION=20101203 foo bar';
var_dump( preg_replace('/VERSION=[0-9]{8}/', 'replacement', $content));
OUTPUT
string(23) "foo replacement foo bar"
Well it was solved with Jason McCreary's suggestion. It worked just without ^ and the rest of the code is the same as I had it before.
I was trying to change the string VERSION=YEARMONTHDAY (which is in one of the lines of the $ks file). I mean that the file contains in one of its lines this: VERSION=20101203 (or any other date, but everytime with the same format)
That string is going to be changed by a new one that matches to the last modification of the file stored in the variable $ks. ($ks is the name of the file)
$last_modification = filemtime($ks);
$last_modification = date("Ymd", $last_modification);
// $last_modification (for instance suppose it is VERSION=20110622)
$last_modification="VERSION=" . $last_modification;
// Open the file in order to change the string
$file = $ks;
$fh = fopen($ks, 'r+');
$content = fread($fh, filesize($ks));
$new_content = preg_replace('/VERSION\=[0-9]{8}/', $last_modification, $content);
fclose($fh);
// Open the file in order to write inside it
$fh = fopen($ks, 'r+');
fwrite($fh, $new_content);
fclose($fh);
So the final result is going to be: the file named $ks will have a line with VERSION=20110622 instead of the VERSION=20101203 (or any other older date) string.
The code is working fine this way for me. Thank you all again, I don't know if I have to close this issue, as it is solved
PD: Sorry for my english
精彩评论