PHPackages                             rosell-dk/dom-util-for-webp - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. rosell-dk/dom-util-for-webp

ActiveLibrary

rosell-dk/dom-util-for-webp
===========================

Replace image URLs found in HTML

0.7.1(2y ago)2316.7k↓28.3%4[8 issues](https://github.com/rosell-dk/dom-util-for-webp/issues)[1 PRs](https://github.com/rosell-dk/dom-util-for-webp/pulls)4MITPHP

Since Jan 27Pushed 2y ago2 watchersCompare

[ Source](https://github.com/rosell-dk/dom-util-for-webp)[ Packagist](https://packagist.org/packages/rosell-dk/dom-util-for-webp)[ GitHub Sponsors](https://github.com/rosell-dk)[ Fund](https://ko-fi.com/rosell)[ RSS](/packages/rosell-dk-dom-util-for-webp/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (5)Versions (21)Used By (4)

dom-util-for-webp
=================

[](#dom-util-for-webp)

[![Latest Stable Version](https://camo.githubusercontent.com/5973395abe1085f9c0982c0a3ea371ac3420778cf5715b52dcefd37a7f45245f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f726f73656c6c2d646b2f646f6d2d7574696c2d666f722d776562702e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/rosell-dk/dom-util-for-webp)[![Minimum PHP Version](https://camo.githubusercontent.com/86e7d829a466cacd5658a22073e27d49d39dac72cc18216ac4963ed5463c5bbc/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344253230352e362d3838393242462e7376673f7374796c653d666c61742d737175617265)](https://php.net)[![Build Status](https://camo.githubusercontent.com/6e0f5f4198bb23a3410cd327ce8c0b7a67c902e6b0c6812127a60053f50d13a8/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f726f73656c6c2d646b2f646f6d2d7574696c2d666f722d776562702f63692e796d6c3f6272616e63683d6d6173746572266c6f676f3d476974487562267374796c653d666c61742d737175617265266c6162656c3d6275696c64)](https://github.com/rosell-dk/dom-util-for-webp/actions/workflows/ci.yml)[![Coverage](https://camo.githubusercontent.com/d7707e0e69fc38927c4c061c7f0e2294b86b5e142c4423b498f6bf6296b652e8/68747470733a2f2f696d672e736869656c64732e696f2f656e64706f696e743f75726c3d68747470733a2f2f6c6974746c652d622e69742f646f6d2d7574696c2d666f722d776562702f636f64652d636f7665726167652f636f7665726167652d62616467652e6a736f6e)](http://little-b.it/dom-util-for-webp/code-coverage/coverage/index.html)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](https://github.com/rosell-dk/dom-util-for-webp/blob/master/LICENSE)[![Dependents](https://camo.githubusercontent.com/1d6982e02d8cd92d478411fed636d05054a192380745677ca88e40228b420765/687474703a2f2f706f7365722e707567782e6f72672f726f73656c6c2d646b2f646f6d2d7574696c2d666f722d776562702f646570656e64656e7473)](https://packagist.org/packages/rosell-dk/dom-util-for-webp/dependents?order_by=downloads)

*Replace image URLs found in HTML*

This library can do two things:

1. Replace image URLs in HTML
2. Replace *&lt;img&gt;* tags with *&lt;picture&gt;* tags, adding webp versions to sources

To setup with composer, run `composer require rosell-dk/dom-util-for-webp`.

1. Replacing image URLs in HTML
-------------------------------

[](#1-replacing-image-urls-in-html)

The *ImageUrlReplacer::replace($html)* method accepts a piece of HTML and returns HTML where where all image URLs have been replaced - even those in inline styles.

*Usage:*

```
$modifiedHtml = ImageUrlReplacer::replace($html);
```

### Example replacements:

[](#example-replacements)

*input:*

```

#hero {
    background: lightblue url("image.png") no-repeat fixed center;;
}

```

*output:*

```

#hero {
    background: lightblue url("image.png.webp") no-repeat fixed center;;
}

```

Default behaviour of *ImageUrlReplacer::replace*:

- The modified URL is the same as the original, with ".webp" appended (to change, override the `replaceUrl` function)
- Only replaces URLs that ends with "png", "jpg" or "jpeg" (no query strings either) (to change, override the `replaceUrl` function)
- Attribute search/replace limits to these tags: *&lt;img&gt;*, *&lt;source&gt;*, *&lt;input&gt;* and *&lt;iframe&gt;* (to change, override the `$searchInTags` property)
- Attribute search/replace limits to these attributes: "src", "src-set" and any attribute starting with "data-" (to change, override the `attributeFilter` function)
- Urls inside styles are replaced too (*background-image* and *background* properties)

The behaviour can be modified by extending *ImageUrlReplacer* and overriding public methods such as *replaceUrl*

ImageUrlReplacer uses the `Sunra\PhpSimple\HtmlDomParser`[library](https://github.com/sunra/php-simple-html-dom-parser) for parsing and modifying HTML. It wraps [simplehtmldom](http://simplehtmldom.sourceforge.net/). Simplehtmldom supports invalid HTML (it does not touch the invalid parts)

### Example: Customized behaviour

[](#example-customized-behaviour)

```
class ImageUrlReplacerCustomReplacer extends ImageUrlReplacer
{
    public function replaceUrl($url) {
        // Only accept urls ending with "png", "jpg", "jpeg"  and "gif"
        if (!preg_match('#(png|jpe?g|gif)$#', $url)) {
            return;
        }

        // Only accept full urls (beginning with http:// or https://)
        if (!preg_match('#^https?://#', $url)) {
            return;
        }

        // PS: You probably want to filter out external images too...

        // Simply append ".webp" after current extension.
        // This strategy ensures that "logo.jpg" and "logo.gif" gets counterparts with unique names
        return $url . '.webp';
    }

    public function attributeFilter($attrName) {
        // Don't allow any "data-" attribute, but limit to attributes that smells like they are used for images
        // The following rule matches all attributes used for lazy loading images that we know of
        return preg_match('#^(src|srcset|(data-[^=]*(lazy|small|slide|img|large|src|thumb|source|set|bg-url)[^=]*))$#i', $attrName);

        // If you want to limit it further, only allowing attributes known to be used for lazy load,
        // use the following regex instead:
        //return preg_match('#^(src|srcset|data-(src|srcset|cvpsrc|cvpset|thumb|bg-url|large_image|lazyload|source-url|srcsmall|srclarge|srcfull|slide-img|lazy-original))$#i', $attrName);
    }
}

$modifiedHtml = ImageUrlReplacerCustomReplacer::replace($html);
```

2. Replacing *&lt;img&gt;* tags with *&lt;picture&gt;* tags
-----------------------------------------------------------

[](#2-replacing-img-tags-with-picture-tags)

The *PictureTags::replace($html)* method accepts a piece of HTML and returns HTML where where all &lt;img&gt; tags have been replaced with &lt;picture&gt; tags, adding webp versions to sources

Usage:

```
$modifiedHtml = PictureTags::replace($html);
```

#### Example replacements:

[](#example-replacements-1)

*Input:*

```

```

*Output*:

```

'
```

Note that with the picture tags, it is still the img tag that shows the selected image. The picture tag is just a wrapper. So it is correct behaviour not to copy the *style*, *width*, *class* or any other attributes to the picture tag. See [issue #9](https://github.com/rosell-dk/dom-util-for-webp/issues/9).

As with `ImageUrlReplacer`, you can override the *replaceUrl* function. There is however currently no other methods to override.

`PictureTags` currently uses regular expressions to do the replacing. There are plans to change implementation to use `Sunra\PhpSimple\HtmlDomParser`, like our `ImageUrlReplacer` class does.

Platforms
---------

[](#platforms)

Works on (at least):

- OS: Ubuntu (22.04, 20.04, 18.04), Windows (2022, 2019), Mac OS (13, 12, 11, 10.15)
- PHP: 5.6 - 8.2 (also tested 8.3 and 8.4 development versions in October 2023)

Each new release will be tested on all combinations of OSs and PHP versions that are [supported](https://github.com/marketplace/actions/setup-php-action) by GitHub-hosted runners. Except that we do not below PHP 5.6.
Status: [![Build Status](https://camo.githubusercontent.com/a8df759c242d8fa464758a2b7876b71e6aaee8b178b053a3c66cb29bc21cbbf0/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f726f73656c6c2d646b2f646f6d2d7574696c2d666f722d776562702f72656c656173652e796d6c3f6272616e63683d6d6173746572266c6f676f3d476974487562267374796c653d666c61742d737175617265266c6162656c3d4769616e7425323074657374)](https://github.com/rosell-dk/dom-util-for-webp/actions/workflows/release.yml)

Testing consists of running the unit tests. The code in this library is almost completely covered by tests (~95% coverage).

We also test future versions of PHP monthly, in order to catch problems early.
Status: [![PHP 8.3](https://camo.githubusercontent.com/5e1002be5a4b129ddf32eda6e36c614fc79d5e2be6f97a83c381824742b237cc/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f726f73656c6c2d646b2f646f6d2d7574696c2d666f722d776562702f70687038332e796d6c3f6272616e63683d6d6173746572266c6f676f3d476974487562267374796c653d666c61742d737175617265266c6162656c3d504850253230382e33)](https://github.com/rosell-dk/dom-util-for-webp/actions/workflows/php83.yml)[![PHP 8.4](https://camo.githubusercontent.com/6475ae726e4e58bd92fa3df8044621124679aef659af44353b1bc5a05ed88d45/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f726f73656c6c2d646b2f646f6d2d7574696c2d666f722d776562702f70687038342e796d6c3f6272616e63683d6d6173746572266c6f676f3d476974487562267374796c653d666c61742d737175617265266c6162656c3d504850253230382e34)](https://github.com/rosell-dk/dom-util-for-webp/actions/workflows/php84.yml)

Do you like what I do?
----------------------

[](#do-you-like-what-i-do)

Perhaps you want to support my work, so I can continue doing it :)

- [Become a backer or sponsor on Patreon](https://www.patreon.com/rosell).
- [Buy me a Coffee](https://ko-fi.com/rosell)

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance13

Infrequent updates — may be unmaintained

Popularity37

Limited adoption so far

Community18

Small or concentrated contributor base

Maturity59

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 99.4% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~90 days

Recently: every ~133 days

Total

20

Last Release

941d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/17592708?v=4)[Bjørn Rosell](/maintainers/rosell-dk)[@rosell-dk](https://github.com/rosell-dk)

---

Top Contributors

[![rosell-dk](https://avatars.githubusercontent.com/u/17592708?v=4)](https://github.com/rosell-dk "rosell-dk (153 commits)")[![zcorpan](https://avatars.githubusercontent.com/u/244772?v=4)](https://github.com/zcorpan "zcorpan (1 commits)")

---

Tags

htmlimagesWebpreplace

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/rosell-dk-dom-util-for-webp/health.svg)

```
[![Health](https://phpackages.com/badges/rosell-dk-dom-util-for-webp/health.svg)](https://phpackages.com/packages/rosell-dk-dom-util-for-webp)
```

###  Alternatives

[ezyang/htmlpurifier

Standards compliant HTML filter written in PHP

3.3k327.6M445](/packages/ezyang-htmlpurifier)[phpoffice/phpword

PHPWord - A pure PHP library for reading and writing word processing documents (OOXML, ODF, RTF, HTML, PDF)

7.6k34.7M186](/packages/phpoffice-phpword)[nette/utils

🛠 Nette Utils: lightweight utilities for string &amp; array manipulation, image handling, safe JSON encoding/decoding, validation, slug or strong password generating etc.

2.1k394.3M1.5k](/packages/nette-utils)[masterminds/html5

An HTML5 parser and serializer.

1.8k242.8M229](/packages/masterminds-html5)[rosell-dk/webp-convert

Convert JPEG &amp; PNG to WebP with PHP

6038.1M54](/packages/rosell-dk-webp-convert)[league/html-to-markdown

An HTML-to-markdown conversion helper for PHP

1.9k28.6M199](/packages/league-html-to-markdown)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
