From 8b8c03960a9f25a1589f7ff8dd245ac8641d89f3 Mon Sep 17 00:00:00 2001 From: Andrei Telteu Date: Tue, 15 Oct 2024 15:58:53 +0300 Subject: [PATCH] 0.17 replace str_replace_limit --- README.md | 4 ++++ src/CustombergInstance.php | 18 +++++++++++++++--- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 6639615..47e3263 100644 --- a/README.md +++ b/README.md @@ -88,6 +88,10 @@ Enjoy ! # Changelog: +### v0.17 - 2024-10-15 + +- Replace str_replace_limit implementation because there is a character limit error + ### v0.16 - 2024-10-14 - New field type: `custom` for custom js field with React.createElement diff --git a/src/CustombergInstance.php b/src/CustombergInstance.php index 7454aae..70b6bf2 100644 --- a/src/CustombergInstance.php +++ b/src/CustombergInstance.php @@ -229,10 +229,22 @@ public function render($html, $lang = null) } } -function str_replace_limit($find, $replacement, $subject, $limit = 0) -{ +function str_replace_limit($find, $replacement, $subject, $limit = 0) { + // If no limit is set, use regular str_replace if ($limit == 0) { return str_replace($find, $replacement, $subject); } - return preg_replace('/' . preg_quote($find, '/') . '/', $replacement, $subject, $limit); + $pos = 0; // Position to start searching + $count = 0; // Keep track of how many replacements we've made + while (($pos = strpos($subject, $find, $pos)) !== false) { + // Replace only up to the limit + if (++$count > $limit) { + break; + } + // Perform the replacement + $subject = substr_replace($subject, $replacement, $pos, strlen($find)); + // Move the position forward by the length of the replacement + $pos += strlen($replacement); + } + return $subject; }