Replacing lines in a file
<?php
$for_edit = "подробнее"; // искомая строка 1
$for_edit2 = "подробнее2"; // искомая строка 2
$what = "кратко"; // на эту меняем
$fopen = @file("21.txt");
foreach ($fopen as $key => $value) {
if (substr_count($value, $for_edit)) {
if (isset($fopen[$key + 1])) {
array_splice($fopen, $key + 1, 1, $what);
}
}
$f = fopen("21.txt", "w");
for ($i = 0; $i < count($fopen); $i++) {
fwrite($f, $fopen[$i]);
}
fclose($f);
}
?>
The script is looking for a specific line and changes the next one to the desired one, how do I make the script look for 2 specific lines and change everything in between to the desired line? (Even though I can't format the text.)
0
Author: Nicolas Chabanovsky, 2011-09-26
3 answers
function getBetween($s1, $s2, $str)
{
$s = strpos($str, $s1) + strlen($s1);
$e = strpos($str, $s2);
return substr($str, $s, $e-$s);
}
echo getBetween('<img ', ' />', '<img src="lalala.gif" alt="lalala song" />');
How to replace, I think you can guess? =)
1
Author: ling, 2011-09-26 12:33:56
Alternatively, a function that finds and replaces all matches between the search strings:
function replaceBetween($s1,$put,$s2,$str){
$s = explode($s1,$str);
foreach($s as $k=>$r){
$n=strpos($r,$s2);
$out .= ($n?$s1.$put:($k?$s1:'')).substr($r,$n);
}
return $out;
}
//использование в вашем случае:
echo replaceBetween($for_edit,$what,$for_edit2,file_get_contents('21.txt'));
0
Author: DL_, 2011-09-26 18:18:27
As an option (I will not paint the entire script, I think you will understand):
$text; // содержимое нашего файла
$str1; // Строка 1
$str2; // Строка 2
$to_r; // Текст на который будет меняться информация между строкой 1 и 2
preg_replace('#('.$str1.').*('.$str2.')#msi', '$1'.$to_r.'$2', $text);
0
Author: Даниил Вендолин, 2011-09-26 18:28:52