0

I am trying to make a PHP function that replaces all occurrences between two strings for an another given string.

I am almost sure I have accomplished what I was looking for, however while I was programming I had two versions of it. I would like you guys explain me which one is better.

Version 1:

$html = "{tag param1|param2}<adfasdfsdf>adsfasdf<adsfasdfsd>{tag param1} {tag param2} sdfsdfadsfasdf";
$needle = array('{tag ', '}');
$placeholder = 'TEST';
$lengths = array(strlen($needle[0]), strlen($needle[1]), strlen($placeholder));
$offset = 0;
while(($startpos = strpos($html, $needle[0], $offset)) !== false){
    $endpos = strpos($html, $needle[1], $startpos + $lengths[0]);
    if($endpos === false) break;
    $html = substr_replace($html, $placeholder, $startpos, $endpos - $startpos + 1);
    $offset = $startpos + $lengths[2];
}
echo $html;

Version 2:

$html = "{tag param1|param2}<adfasdfsdf>adsfasdf<adsfasdfsd>{tag param1} {tag param2} sdfsdfadsfasdf";
$needle = array('{tag ', '}');
$placeholder = 'TEST';
$offset = 0;
while(($startpos = strpos($html, $needle[0], $offset)) !== false){
    $endpos = strpos($html, $needle[1], $startpos + strlen($needle[0]));
    if($endpos === false) break;
    $html = substr_replace($html, $placeholder, $startpos, $endpos - $startpos + 1);
    $offset = $startpos + strlen($placeholder);
}
echo $html;

This code search for all {tag ...........} occurrences and replace them for TEST.

I know at this point this might be micro optimization, however I would like to learn.

Any error you see or suggestion is welcome.

Script47
  • 14,230
  • 4
  • 45
  • 66
Exprove
  • 1,301
  • 2
  • 18
  • 32
  • 2
    Maybe https://codereview.stackexchange.com is better suited for this question? – Script47 Sep 03 '18 at 09:11
  • @Script47 I was about to post it on code review, but this is kinda a question and not code review, 'Does PHP optimize multiple strlen calls on for loop?'. For another hand yes I might have expose this question as a code review, but it is not. – Exprove Sep 03 '18 at 09:21
  • To my knowledge cross-site posts are not against the rules, so you could post the question on CR too but with a greater focus on comparing the two snippets and leave the question part of your question on SO. – Script47 Sep 03 '18 at 09:25
  • 1
    Manually hoisting `strlen` is probably not a bad thing (for style and/or performance), but keeping the result in named variables like `$placeholder_len`would make the code in the loop more meaningful than `$lengths[2]`. I'd be surprised if a PHP interpreter could cache or hoist `strlen` out of the loop for you, but maybe if those strings aren't being modified. – Peter Cordes Sep 03 '18 at 22:25

0 Answers0