From 523cdaa7f484d09e5198bdeb23dc2b42bdac05e7 Mon Sep 17 00:00:00 2001 From: Joshua Ramon Enslin Date: Sun, 9 Aug 2020 00:59:41 +0200 Subject: [PATCH] Add type-safe wrapper around preg_replace for replacing in strings --- MD_STD.php | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/MD_STD.php b/MD_STD.php index 37bc600..61b99b2 100644 --- a/MD_STD.php +++ b/MD_STD.php @@ -115,6 +115,26 @@ class MD_STD { } + /** + * Type-safe(r) wrapper around preg_replace. + * + * @param string $pattern The pattern to search for. It can be either a string or an array with strings. + * @param string $replacement To replace with. + * @param string $subject The string or an array with strings to search and replace. + * + * @return string + */ + public static function preg_replace_str(string $pattern, string $replacement, string $subject):string { + + $output = preg_replace($pattern, $replacement, $subject); + if ($output === null) { + throw new Exception("Error replacing in $subject: Replacing $pattern with $replacement"); + } + + return $output; + + } + /** * Type-safe wrapper around json_encode. *