larust_support/regex_replace.rs
1//! `preg_replace($pattern, $replacement, $subject)` support - the target
2//! of `larust-convert`'s Blade expression translator (`larust_convert::
3//! blade::expr::translate`'s `"preg_replace"` arm). That translator only
4//! ever emits a call here after already compiling the *same* pattern
5//! literal with this exact `regex` crate at convert time (its own
6//! self-check, mirroring `syn::parse_str::<syn::Expr>`'s role everywhere
7//! else in that translator) - so [`replace_all`]'s pattern argument is
8//! never expected to fail to compile for converter-generated call sites.
9//! It still doesn't panic on one that does (a hand-written call, or a
10//! pattern edited after conversion): falling back to returning `subject`
11//! unchanged is the same "never fail, best-effort" choice
12//! `larust_support::date::strtotime` already makes, for the same reason -
13//! this is a runtime helper, not the converter's own convert-time
14//! rejection path.
15
16/// Replaces every match of `pattern` (a Rust `regex`-syntax pattern -
17/// `larust-convert` is responsible for translating PHP's PCRE delimiter/
18/// flag syntax into this form before ever generating a call here) in
19/// `subject` with `replacement`, which may use `$1`-style backreferences
20/// exactly like PHP's own `preg_replace` replacement string.
21/// `replacement`/`subject` accept both `String` and `&str` so the
22/// converter's own translated sub-expressions (a string literal, or a
23/// `format!(...)`-produced `String` from a `.`-concatenation) both work
24/// as call-site arguments without the converter needing to know which
25/// shape it produced.
26pub fn replace_all(
27 pattern: &str,
28 replacement: impl AsRef<str>,
29 subject: impl AsRef<str>,
30) -> String {
31 match regex::Regex::new(pattern) {
32 Ok(re) => re
33 .replace_all(
34 subject.as_ref(),
35 braced_backreferences(replacement.as_ref()).as_str(),
36 )
37 .into_owned(),
38 Err(_) => subject.as_ref().to_string(),
39 }
40}
41
42/// PHP's `$N` backreference in a `preg_replace` replacement string takes
43/// the longest run of *digits* after `$` - `$1h` is group `1` followed by
44/// literal `h`, since `h` isn't a digit. Rust's `regex` crate's bare
45/// `$name` replacement syntax instead takes the longest run of
46/// *identifier* characters (`[0-9A-Za-z_]+`), so that same `$1h` would
47/// look for a named group `"1h"` and (finding none) silently substitute
48/// nothing - a real, silent-data-loss bug this exists to close. Rewriting
49/// every bare `$<digits>` to `${<digits>}` (braces disambiguate
50/// unconditionally in Rust regex's syntax) before it ever reaches
51/// `Regex::replace_all` matches PHP's own semantics regardless of what
52/// character immediately follows the backreference in the (possibly
53/// runtime-computed) replacement string. `$$` (Rust regex's own escape
54/// for a literal `$`) and an already-braced `${...}` both pass through
55/// unchanged. One known, accepted gap: PHP/PCRE backs a multi-digit
56/// reference like `$12` off to `$1` + literal `2` when there's no 12th
57/// capture group - this always takes the *whole* leading digit run as one
58/// group number instead, matching the common single-digit case this
59/// exists for but not that fallback behavior.
60fn braced_backreferences(replacement: &str) -> String {
61 let mut out = String::with_capacity(replacement.len());
62 let mut chars = replacement.chars().peekable();
63 while let Some(c) = chars.next() {
64 if c != '$' {
65 out.push(c);
66 continue;
67 }
68 if chars.peek() == Some(&'$') {
69 out.push('$');
70 out.push(chars.next().unwrap());
71 continue;
72 }
73 let mut digits = String::new();
74 while let Some(&d) = chars.peek() {
75 if d.is_ascii_digit() {
76 digits.push(d);
77 chars.next();
78 } else {
79 break;
80 }
81 }
82 if digits.is_empty() {
83 out.push('$');
84 } else {
85 out.push_str("${");
86 out.push_str(&digits);
87 out.push('}');
88 }
89 }
90 out
91}
92
93#[cfg(test)]
94mod tests {
95 use super::*;
96
97 #[test]
98 fn replaces_every_match_using_a_backreference_in_the_replacement() {
99 let out = replace_all(
100 r#"(^|["'(\s])\/storage"#,
101 "$1https://cdn.example.com/storage",
102 r#"<img src="/storage/x.png"> /storage/y.png"#,
103 );
104 assert_eq!(
105 out,
106 r#"<img src="https://cdn.example.com/storage/x.png"> https://cdn.example.com/storage/y.png"#
107 );
108 }
109
110 #[test]
111 fn a_backreference_immediately_followed_by_a_word_character_is_disambiguated() {
112 // Without `braced_backreferences`, Rust's regex crate reads
113 // `$1h` as a request for a named group `"1h"` (none exists) and
114 // silently drops it - PHP reads it as group `1` then literal
115 // `h`. This is the exact real-world shape: rewriting a stored
116 // path into a URL, where the captured delimiter (`$1`) is
117 // immediately followed by the replacement host.
118 let out = replace_all("a(b)c", "$1https://x", "abc");
119 assert_eq!(out, "bhttps://x");
120 }
121
122 #[test]
123 fn a_literal_dollar_sign_escaped_as_dollar_dollar_passes_through() {
124 let out = replace_all("a", "$$5", "a");
125 assert_eq!(out, "$5");
126 }
127
128 #[test]
129 fn no_match_leaves_the_subject_unchanged() {
130 let out = replace_all("nope", "x", "hello world");
131 assert_eq!(out, "hello world");
132 }
133
134 #[test]
135 fn an_invalid_pattern_falls_back_to_the_subject_unchanged_instead_of_panicking() {
136 let out = replace_all("(unterminated", "x", "hello world");
137 assert_eq!(out, "hello world");
138 }
139
140 #[test]
141 fn accepts_both_owned_and_borrowed_replacement_and_subject() {
142 let owned_subject = String::from("a/storage/b");
143 let owned_replacement = String::from("x");
144 assert_eq!(
145 replace_all(r"/storage", &owned_replacement, &owned_subject),
146 "ax/b"
147 );
148 assert_eq!(replace_all(r"/storage", "x", "a/storage/b"), "ax/b");
149 }
150}