Andy_K Posted May 1, 2018 Share Posted May 1, 2018 Hello, I've currently got an issue where when using preg_replace in a forloop, it duplicates code: The code I'm using is: function GenerateSwitchDiagram($Code) { $Html = ""; $SwitchCount = preg_match_all('/\\[Switch(.|\n)*?\[EndSwitch]/', $Code, $SwitchContent); for($Switch = 0; $Switch < $SwitchCount; $Switch++) { preg_match_all('/\[Switch\s*([^\]]*)\s*\]/', $SwitchContent[0][$Switch], $SwitchTags, PREG_SET_ORDER); preg_match_all('/([^=\s]+)="([^"]+)"/', $SwitchTags[0][1], $SwitchInfo, PREG_SET_ORDER); $Name = $SwitchInfo[0][2]; $Size = $SwitchInfo[1][2]; $Html .= '<div class="SwitchContainer SwitchSize_' . $Size . '">'; $Html .= '<div class="SwitchName">' . $Name . '</div>'; for($Port = 1; $Port <= $Size; $Port++) { if(preg_match_all('/\[Port' . $Port . ' \s*([^\]]*)\s*\]/', $SwitchContent[0][$Switch], ${'Port' . $Port}, PREG_SET_ORDER) == 1) { preg_match_all('/([^=\s]+)="([^"]+)"/', ${'Port' . $Port}[0][1], $PortInfo, PREG_SET_ORDER); $Comment = $PortInfo[0][2]; $Mode = $PortInfo[1][2]; $VLANS = $PortInfo[2][2]; $Html .= '<div class="SwitchPort PortLive">'; $Html .= $Port; $Html .= '<span class="SwitchComment"><strong>Comment:</strong> ' . $Comment . '<br /><strong>Mode:</strong> ' . $Mode . '<br /><strong>VLAN(s):</strong> ' . $VLANS . '</span>'; $Html .= '</div>'; } else { $Html .= '<div class="SwitchPort PortDown">'; $Html .= $Port; $Html .= '</div>'; } } $Html .= '</div>'; $Code = preg_replace('/\[Switch Name="' . $Name . '" Size="' . $Size . '"](.|\n)*?\[EndSwitch]/', $Html, $Code); } return $Code; } I've had a look and it looks like I should be using preg_replace_callback() rather than preg_replace, but I need to replace dynamic strings, not static so I'm not sure how I would replace the following line to use preg_replace_callback(): $Code = preg_replace('/\[Switch Name="' . $Name . '" Size="' . $Size . '"](.|\n)*?\[EndSwitch]/', $Html, $Code); Thanks, Andy Quote Link to comment https://forums.phpfreaks.com/topic/307242-preg_replace-in-for-loop-issues/ Share on other sites More sharing options...
Solution Andy_K Posted May 1, 2018 Author Solution Share Posted May 1, 2018 I can't seem to edit my last post, but I've resolved the issue. - Bad placement of the $Html variable. Should have been under the first for loop rather than above it. Quote Link to comment https://forums.phpfreaks.com/topic/307242-preg_replace-in-for-loop-issues/#findComment-1558238 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.