@@ -933,4 +933,59 @@ public static function clearFiles(Carbon $minAge = null, string $directory = nul
933933
934934 return count ($ files );
935935 }
936+
937+ /**
938+ * Parse a given HTML string for images and replace them with the resized copies as per the given modifications.
939+ *
940+ * CAUTION: Experimental
941+ *
942+ * This uses regex to find and replace HTML content which is often frowned upon. You may supply your own custom
943+ * regexes, or you may rely on the defaults (which may change in future versions of this plugin soo beware).
944+ *
945+ * By default this will search img elements with a src, data-src or lazy-src attribute, as well as any "style"
946+ * attribute with a background or background-image CSS rule (of which contains a "url()" to an image)
947+ *
948+ * Example Usage (a richeditor field that contains custom embedded images that require OTF optimisation or resizing):
949+ * {{ service.description | filterHtmlImageResize(600, 600, { mode: 'contain' }) }}
950+ * {{ service.description | filterHtmlImageModifiy({ quality: 60 }) }}
951+ *
952+ * @param string $html The HTML to find/replace images
953+ * @param int|null $width
954+ * @param int|null $height
955+ * @param array $options
956+ * @param array $regexes List of regexes (keys) and callbacks (values) to use in the preg_replace_callback.
957+ * @param int $limit See preg_replace_callback $limit docs
958+ * @return string The same HTML but with images replaced with their resized URL equivalents
959+ */
960+ public static function parseFindReplaceImages (
961+ string $ html ,
962+ int $ width = null ,
963+ int $ height = null ,
964+ array $ options = [],
965+ array $ regexes = null ,
966+ int $ limit = 255
967+ ): string {
968+ $ regexes = ($ regexes !== null ) ? $ regexes : [
969+ '/(<img [^>]*(?:src|data-src|lazy-src)=)"([^"]+)"/ ' => function ($ match ) use ($ width , $ height , $ options ) {
970+ $ resizer = new Resizer ((string ) $ match [2 ]);
971+
972+ $ url = $ resizer ->resize ($ width , $ height , $ options );
973+
974+ return $ match [1 ] . '" ' . $ url . '" ' ;
975+ },
976+ '/(style="([^"]*)background(-image)?:(\s*[^"]+)?url\( \'?)(.+?)( \'?\))"/ ' => function ($ match ) use ($ width , $ height , $ options ) {
977+ $ resizer = new Resizer ((string ) $ match [2 ]);
978+
979+ $ url = $ resizer ->resize ($ width , $ height , $ options );
980+
981+ return $ match [1 ] . $ url . $ match [6 ];
982+ },
983+ ];
984+
985+ foreach ($ regexes as $ regex => $ callback ) {
986+ $ html = preg_replace_callback ($ regex , $ callback , $ html , $ limit );
987+ }
988+
989+ return $ html ;
990+ }
936991}
0 commit comments