php - Get everything between strings and replace with something else -
i trying between {code} tags $html string.
so far have written doesn't work expected, replacing first {code}
also work many code tags, haven't gotten far yet.
<?php $html = <<< eot <p>lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> <p>{code}my test code 1{/code}</p> <p>lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> eot; $startpos = strpos($html, '{code}'); $endpos = strpos($html, '{/code}'); if($startpos !== false && $endpos !== false){ $startpos += 6; # strlen('{code}') $endpos += 7; # strlen('{/code}') // code $code = substr($html, $startpos, $endpos); // remove code apart start {code} $html = substr($html, $startpos-6, $endpos); // replace new code $new_code = 'test'; $html = str_replace('{code}', $new_code, $html); } echo $html;
result: - http://codepad.viper-7.com/t9sbbn
testmy test code 1{/code}
lorem ipsum dolor sit amet, consectetur adipiscing elit.
expected result
lorem ipsum dolor sit amet, consectetur adipiscing elit.
test
lorem ipsum dolor sit amet, consectetur adipiscing elit.
this works 1 {code}.
<?php $html = <<< eot <p>lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> <p>{code}my test code 1{/code}</p> <p>lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> eot; $startpos = strpos($html, '{code}'); $endpos = strpos($html, '{/code}'); if($startpos !== false && $endpos !== false){ $startpos += 6; # strlen('{code}') // code $code = substr($html, $startpos, $endpos-$startpos); // replace new code $new_code = 'test'; $html = str_replace('{code}'.$code.'{/code}', $new_code, $html); } echo $html;
multiple this:
<?php $html = <<< eot <p>lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> <p>{code}my test code 1{/code}</p> <p>lorem ipsum dolor sit amet, consectetur adipiscing elit.{code}hi{/code}</p> eot; $html = test($html); echo $html; function test($html){ do{ $startpos = strpos($html, '{code}'); $endpos = strpos($html, '{/code}'); if($startpos !== false && $endpos !== false){ $startpos += 6; # strlen('{code}') // code $code = substr($html, $startpos, $endpos-$startpos); // replace new code $new_code = 'test'; $html = str_replace('{code}'.$code.'{/code}', $new_code, $html); } }while($startpos !== false && $endpos !== false); return $html; }
Comments
Post a Comment