Reputation: 2223
So I have text file that content looks, for example, as folows:
Name: 'John',
Surname: 'Doe',
Age: 35
But I don't know for sure if the current surname is Doe, anything could be generated there.
And I need to replace this surname with another one. So I need to somehow open the file, find the place I need (I know for sure that it starts with Surname: '
and ends with ',
, and I need to replace string between these two substrings, whatever it was before, without breaking the file structure (losing line breaks and so on; the actual file is pretty long, so adding \n manually is not an option).
So far I've tried this
$content = file_get_contents('text.txt');
$search = "/[^Surname: '](.*)[^',]/";
$replace = 'Smith';
$content = preg_replace($search,$replace,$content);
file_put_contents('text.txt', $content);
But it replaces almost everything with 'Smith', because the combination of ',
is pretty common in this file, and also it turns the entire file into one line.
So what could I do to solve my problem? Would highly appreciate any possible help!
UPD: str_replace could be what I need, but first then I need to retrieve the whole line Surname: 'Doe',
from the file to get the current surname.
Upvotes: 0
Views: 3666
Reputation: 412
$text = "Name: 'John',
Surname: 'Doe',
Age: 35";
$search = "/Surname:\s+'(.*?)',/is";
$replace = 'Surname: \'Smith\',';
$content = preg_replace($search, $replace, $text);
echo $content;
Upvotes: 0
Reputation: 222128
I would use the regex /^Surname: '.*',$/m
based on your description and replace it with Surname: 'Smith',
.
Code:
<?php
$content = file_get_contents('text.txt');
$search = "/^Surname: '.*',$/m";
$replace = "Surname: 'Smith',";
$content = preg_replace($search, $replace, $content);
file_put_contents('text.txt', $content);
Demo:
$ cat text.txt
Name: 'John',
Surname: 'Doe',
Age: 35
$ php a.php
$ cat text.txt
Name: 'John',
Surname: 'Smith',
Age: 35
Upvotes: 4