Skip to content

Commit

Permalink
0.17 replace str_replace_limit
Browse files Browse the repository at this point in the history
  • Loading branch information
Andrei Telteu committed Oct 15, 2024
1 parent 5ea0365 commit 8b8c039
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 15 additions & 3 deletions src/CustombergInstance.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

0 comments on commit 8b8c039

Please sign in to comment.