views:

90

answers:

4

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);
+1  A: 

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);
Greg
/in replace me every thing and i get empty string
Haim Evgi
I made a typo the first time - should have been /is
Greg
If you don't want to replace the comments then combine this with @soulmerge's answer
Greg
empty again , sorry
Haim Evgi
Hmm... I don't think there's any way it can give you an empty string - are you sure you haven't made a typo when you print it out?
Greg
another details in this 2 tags i have many lines of html like table, tr , td
Haim Evgi
is was my stupid mistake preg_replace('/<!--\s*start_ticker\s*-->.*?<!--\s*end_ticker\s*-->/is',"bla",$string_html);
Haim Evgi
+1  A: 

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.

soulmerge
get empty string
Haim Evgi
That's not possible. It should at least contain blabla
soulmerge
+1  A: 

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.

bucabay
+2  A: 

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));
    }
}
Gumbo
I recommend this. It should be faster then the PCREs.
bucabay