Question
i want to replace html text that closed by tag
start_ticker code.... end_ticker
i don't success
my code is
$string_html = preg_replace('/<!-- start_ticker -->.*<!-- end_ticker -->/i',"bla bla",$string_html);
Solution
By default "." doesn't match newlines - you can add the "s" (DOTALL) modifier to change this. I suspect that's your problem.
$string_html = preg_replace('/<!-- start_ticker -->.*<!-- end_ticker -->/is',"bla bla",$string_html);
OTHER TIPS
You can solve that problem even without using regular expressions:
$start = '<!-- start_ticker -->';
$end = '<!-- end_ticker -->';
$replacement = 'blabla';
$posStart = stripos($str, $start);
if ($posStart !== false) {
$posEnd = stripos($str, $end, $posStart);
if ($posEnd !== false) {
$str = substr($str, 0, $posStart) . $replacement . substr($str, $posEnd + strlen($end));
}
}
I guess you want to keep the start/end tags. Then you need to capture them with brackets:
$string_html = preg_replace('/(<!-- start_ticker -->).*(<!-- end_ticker -->)/i', '$1bla bla$2', $string_html);
Beware though, that regular expressions are not the best choice when it comes to html.
You need:
$match1 = '<!-- start_ticker -->';
$match2 = '<!-- end_ticker -->';
$replace = 'bla bla';
$string = preg_replace("/$match1(.*?)$match2/is", $match1.$replace.$match2, $string);
Note that (.*?) makes a large difference since it makes the match ungreedy. This is when the pattern will be matched to the largest number of possible permutations of that pattern, rather then the least.
http://www.troubleshooters.com/codecorn/littperl/perlreg.htm#Greedy
Otherwise, you would match from the first to the last clobbering anything in between if there are multiple matches.