Consider an example with xnotes :

$filename = 'file.txt'; $file = file_get_contents($filename); $file = str_replace('foo', 'bar', $file); file_put_contents($filename, $file); 

How to make a similar replacement, only:

  • We will replace in advance the unknown contents of some tag, for example, <title>
  • Deletion of deletions in the source file should not be

I tried this:

 $filename = 'file.php'; $file = file_get_contents($filename); $title_pattern='#<title>.+?</title>#s'; $test= str_replace($title_pattern, "Новый заголовок", $file); file_put_contents($file, $test); 

and another way:

 $title_pattern='#<title>.+?</title>#s'; preg_match($title_pattern, $file, $matches); $test= str_replace($matches, "Новый заголовок", $file); file_put_contents($fileadr, $test) 

Ideally, you need to go to the file, which at the moment is not displayed in the browser, replace only the content of one tag, and do not touch the rest of what is there and do not even read it (we simply do not need it). But I suspect that this is beyond the capabilities of PHP.

Still through PHPQuery tried to do. As a result, it was possible, but the entire tabulation in the source file was broken (asked a question on this topic, so far without an answer).

  • If the length of the cut part of the line does not coincide with the replacement "not even read" will not work. After all, it will be necessary to move all the text after the place of replacement by the difference in length - tutankhamun
  • Yes, you need to replace the content with something else that is equal in length to the characters that are already there. BUT it is so if there is a tabulation on the same line, if on others it will not be affected if you have line breaks that separate the tabs. But in general, why make tabulation using text? Isn't it easier to implement it through styles? - Daniel Protopopov
  • I'm not talking about tabs in the text displayed in the browser, but about tabs in HTML code. Why do you need it, you know, because removing a tab makes it difficult to read the code. - Hokov Gleb

1 answer 1

Like this:

 $filename = 'file.php'; $file = file_get_contents($filename); $title_pattern='#<title>(.*)?</title>#s'; $test= preg_replace($title_pattern, "<title>Новый заголовок</title>", $file); file_put_contents($filename, $test); 
  • Great, it works! Thank you for the answer! - Lateral Gleb