5

I have txt file with content:

fggfhfghfghf

$config['website'] = 'Olpa';


asdasdasdasdasdas

And PHP script for replacing by preg_replace in file:

write_file('tekst.txt', preg_replace('/\$config\[\'website\'] = \'(.*)\';/', 'aaaaaa', file_get_contents('tekst.txt')));

But it doesn't work exactly what I want it to work.

Because this script replace whole match, and after change it looks like this:

fggfhfghfghf

aaaaaa


asdasdasdasdasdas

And that's bad.

All I want is to not change whole match $config['website'] = 'Olpa'; But to just change this Olpa

enter image description here

As you can see it belongs not to Group 2. of match information.

And all I want is to just change this Group 2. one specific thing.

to finally after script it will look like:

fggfhfghfghf

$config['website'] = 'aaaaaa';


asdasdasdasdasdas
0

2 Answers 2

11

You need to change your preg_replace to

preg_replace('/(\$config\[\'website\'] = \').*?(\';)/', '$1aaaaaa$2', file_get_contents('tekst.txt'))

It means, capture what you need to keep (and then use backreferences to restore the text) and just match what you need to replace.

See the regex demo.

Pattern details:

  • (\$config\[\'website\'] = \') - Group 1 capturing a literal $config['website'] = ' substring (later referenced to with $1)
  • .*? - any 0+ chars other than line break chars as few as possible
  • (\';) - Group 2: a ' followed with ; (later referenced to with $2)

In case your aaa actually starts with a digit, you would need a ${1} backreference.

Sign up to request clarification or add additional context in comments.

Comments

2

I have a better, faster, leaner solution for you. No capture groups are required, it only requires careful attention to escaping the single quotes:

Pattern: \$config\['website'] = '\K[^']+

\K means "start the fullstring match here", this combined with the negated character class ([^']+) affords the omission of capture groups.

Pattern Demo (just 25 steps)

PHP Implementation:

$txt='fggfhfghfghf

$config[\'website\'] = \'Olpa\';


asdasdasdasdasdas';
print_r(preg_replace('/\$config\[\'website\'\] = \'\K[^\']+/','aaaaaa',$txt));

Using single quotes around the pattern is crucial so that $config isn't interpreted as a variable. As a result, all of the single quotes inside of the pattern must be escaped.

Output:

fggfhfghfghf

$config['website'] = 'aaaaaa';


asdasdasdasdasdas

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.