Commit 423fd33be55 for php
commit 423fd33be55fe3cb341ceef82f820b9ecbcf9974
Author: Weilin Du <weilindu@php.net>
Date: Sun Nov 29 12:59:56 2026 +0800
ext/standard: Avoid redundant searches in str_replace() (#25851)
Reuse the first match from the counting pass and stop copying
matches at the last known match end. When all matches are
adjacent, advance directly to the next match.
diff --git a/UPGRADING b/UPGRADING
index fcff11aabf0..8f954dd01e1 100644
--- a/UPGRADING
+++ b/UPGRADING
@@ -247,6 +247,8 @@ PHP 8.7 UPGRADE NOTES
. Improved performance of array_chunk() when not preserving keys.
. Improved performance of array_splice() when inserting without removing
elements.
+ . Improved performance of str_replace() when the search string is longer than
+ one byte and the replacement has a different length.
. Improved performance of str_rot13().
. Improved performance of pack() for large strings using the a, A and Z
formats.
diff --git a/ext/standard/string.c b/ext/standard/string.c
index 4f9f8b99004..4d7e4121c92 100644
--- a/ext/standard/string.c
+++ b/ext/standard/string.c
@@ -3337,12 +3337,12 @@ static zend_string *php_str_to_str_ex(zend_string *haystack,
return new_str;
} else {
size_t count = 0;
- const char *o = ZSTR_VAL(haystack);
- const char *n = needle;
- const char *endp = o + ZSTR_LEN(haystack);
+ const char *last_match_end = ZSTR_VAL(haystack);
+ end = last_match_end + ZSTR_LEN(haystack);
+ const char *first_match = php_memnstr(last_match_end, needle, needle_len, end);
- while ((o = (char*)php_memnstr(o, n, needle_len, endp))) {
- o += needle_len;
+ for (r = first_match; r; r = php_memnstr(last_match_end, needle, needle_len, end)) {
+ last_match_end = r + needle_len;
count++;
}
if (count == 0) {
@@ -3359,11 +3359,17 @@ static zend_string *php_str_to_str_ex(zend_string *haystack,
}
e = ZSTR_VAL(new_str);
- end = ZSTR_VAL(haystack) + ZSTR_LEN(haystack);
- for (p = ZSTR_VAL(haystack); (r = (char*)php_memnstr(p, needle, needle_len, end)); p = r + needle_len) {
+ *replace_count += count;
+ p = ZSTR_VAL(haystack);
+ /* If all matches are adjacent, their positions are already known. */
+ bool adjacent = first_match + count * needle_len == last_match_end;
+ for (r = first_match; ; r = adjacent ? p : php_memnstr(p, needle, needle_len, end)) {
e = zend_mempcpy(e, p, r - p);
e = zend_mempcpy(e, str, str_len);
- (*replace_count)++;
+ p = r + needle_len;
+ if (p == last_match_end) {
+ break;
+ }
}
if (p < end) {