PHPackages                             devoashim/regxdomdocument - 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. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. devoashim/regxdomdocument

ActiveLibrary[Parsing &amp; Serialization](/categories/parsing)

devoashim/regxdomdocument
=========================

Pure regex-based DOM manipulation library with React/JSX template literal support. No DOMDocument, no XML parsing - just regex magic!

1.0.3(3mo ago)03MITPHPPHP ^8.0|^8.1|^8.2|^8.3

Since Jan 26Pushed 3mo agoCompare

[ Source](https://github.com/DevOashim/RegX-DomDocument)[ Packagist](https://packagist.org/packages/devoashim/regxdomdocument)[ RSS](/packages/devoashim-regxdomdocument/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (3)Dependencies (1)Versions (4)Used By (0)

regxdomdocument - Complete Guide &amp; Reference
================================================

[](#regxdomdocument---complete-guide--reference)

Pure regex-based DOM manipulation library with **React/JSX Template Literal Support**. No DOMDocument, no XML parsing - just regex magic!

Perfect for preserving exact HTML structure, React/Vue components, and template variables.

Installation
------------

[](#installation)

```
composer require devoashim/regxdomdocument
```

---

Table of Contents
-----------------

[](#table-of-contents)

- [Quick Start](#quick-start)
- [Loading HTML](#loading-html)
- [Finding Elements](#finding-elements)
- [Getting Content](#getting-content)
- [Setting Content](#setting-content)
- [Attributes &amp; Classes](#attributes--classes)
- [Template Literals (React/JSX)](#template-literals-reactjsx)
- [Removing Elements](#removing-elements)
- [Iteration &amp; Filtering](#iteration--filtering)
- [Saving &amp; Output](#saving--output)
- [Advanced Usage - RegexHelper](#advanced-usage---regexhelper)
- [Method Reference](#method-reference)
- [Use Cases](#use-cases)

---

Quick Start
-----------

[](#quick-start)

### Basic HTML Manipulation

[](#basic-html-manipulation)

```
use devoashim\regxdomdocument\XDOM;

$dom = XDOM::load($html);

// Find and modify elements
$dom->find('#app')->setInnerHTML('');
$dom->find('.header')->addClass('active');

echo $dom->html();
```

### Template Literal Generation

[](#template-literal-generation)

Convert static className to dynamic React template literal:

```
$dom = XDOM::loadFromFile('index.html');

// Convert static to dynamic
$dom->find('.stricky-header')
    ->setDynamicClass('isStick', 'stricky-fixed');

// Output HTML
echo $dom->html();
```

**Before:**

```

```

**After:**

```

```

---

Loading HTML
------------

[](#loading-html)

### Returns: `XDOM` instance

[](#returns-xdom-instance)

```
// From string
$dom = XDOM::load($htmlString);

// From file
$dom = XDOM::loadFromFile('/path/to/file.html');

// From Laravel Storage
$path = Storage::disk('public')->path('index.html');
$dom = XDOM::loadFromFile($path);
```

---

Finding Elements
----------------

[](#finding-elements)

### Returns: `RegexNodeCollection`

[](#returns-regexnodecollection)

```
// By ID
$element = $dom->find('#header');
$element = $dom->find('#main-content');

// By Class
$elements = $dom->find('.container');
$elements = $dom->find('.nav-item');

// By Tag
$elements = $dom->find('div');
$elements = $dom->find('nav');
$elements = $dom->find('section');

// Combined Selectors
$element = $dom->find('div#main');        // Tag + ID
$element = $dom->find('section#about');

$elements = $dom->find('div.container');  // Tag + Class
$elements = $dom->find('nav.main-nav');

// Descendant (parent child)
$elements = $dom->find('header nav');
$elements = $dom->find('div .content');
$elements = $dom->find('main section');
```

---

Getting Content
---------------

[](#getting-content)

### String Returns

[](#string-returns)

```
// Get inner HTML (content between tags)
$content = $dom->find('#app')->innerHTML();
// THIS CONTENT
// Returns: "THIS CONTENT"

// Get outer HTML (full element with tags)
$html = $dom->find('#app')->outerHTML();
// Returns: "Content"

// Get text content (strip all HTML)
$text = $dom->find('#app')->text();
// Hello World
// Returns: "Hello World"

// Get complete HTML document
$fullHtml = $dom->html();

// Get attribute value
$value = $dom->find('#app')->attr('data-value');
$id = $dom->find('div')->attr('id');
$class = $dom->find('nav')->attr('class');
```

### Array Returns

[](#array-returns)

```
// Get first element
$first = $dom->find('.item')->first();
// Returns: ['html' => '...', 'position' => ..., 'tag' => '...']

// Get last element
$last = $dom->find('.item')->last();

// Get element by index
$third = $dom->find('.item')->get(2);  // 0-based index

// Get all matches as array
$matches = $dom->find('.item')->getMatches();
// Returns: [
//     ['html' => '1', 'position' => 0, 'tag' => 'div', 'type' => 'full'],
//     ['html' => '2', 'position' => 50, 'tag' => 'div', 'type' => 'full'],
// ]
```

### Boolean &amp; Integer Returns

[](#boolean--integer-returns)

```
// Count elements
$count = $dom->find('.item')->count();
echo "Found $count items";

// Check if has attribute
if ($dom->find('#app')->hasAttr('data-loaded')) {
    echo "Has data-loaded attribute";
}

// Check if has class
if ($dom->find('#app')->hasClass('active')) {
    echo "Has active class";
}

// Check if empty
if ($dom->find('.item')->isEmpty()) {
    echo "No items found";
}

// Check if not empty
if ($dom->find('.item')->isNotEmpty()) {
    echo "Items found!";
}
```

---

Setting Content
---------------

[](#setting-content)

### Returns: `RegexNodeCollection` (chainable)

[](#returns-regexnodecollection-chainable)

```
// Set inner HTML (PRESERVES EXACT CONTENT - no encoding)
$dom->find('#app')->setInnerHTML(' ');
// Perfect for React/Vue components!

// Set outer HTML (replace entire element)
$dom->find('#old')->setOuterHTML('Content');
// Before: ...
// After:  Content

// Set text (HTML encoded for safety)
$dom->find('#title')->setText('Hello & Welcome');
// Output: Hello &amp; Welcome

// Append content (add at end, inside element)
$dom->find('#list')->append('New Item');

// Prepend content (add at start, inside element)
$dom->find('#list')->prepend('First Item');

// Insert before element
$dom->find('#main')->before('Header');

// Insert after element
$dom->find('#main')->after('Footer');
```

---

Attributes &amp; Classes
------------------------

[](#attributes--classes)

### Returns: `RegexNodeCollection` (chainable)

[](#returns-regexnodecollection-chainable-1)

```
// Set single attribute
$dom->find('#app')
    ->attr('data-component', 'main')
    ->attr('data-version', '2.0')
    ->attr('data-loaded', 'true');

// Remove attribute
$dom->find('#app')->removeAttr('data-old');

// Add single class
$dom->find('#app')
    ->addClass('active')
    ->addClass('loaded')
    ->addClass('ready');

// Add multiple classes
$dom->find('.header')->addClasses('active loaded ready');
$dom->find('.header')->addClasses(['active', 'loaded', 'ready']);

// Remove class
$dom->find('#app')
    ->removeClass('old')
    ->removeClass('hidden');

// Toggle class
$dom->find('#app')->toggleClass('active');
// If has 'active' → removes it
// If no 'active' → adds it

// Set all classes (replace existing)
$dom->find('.header')->setClasses('new-class another-class');

// Conditional class (PHP-side)
$dom->find('.header')->conditionalClass('active', $isActive);
```

---

Template Literals (React/JSX)
-----------------------------

[](#template-literals-reactjsx)

### Single Conditional Class

[](#single-conditional-class)

```
$dom->find('.header')->setDynamicClass('isStick', 'sticky-fixed');
```

**Result:**

```

```

### Multiple Conditional Classes

[](#multiple-conditional-classes)

```
$dom->find('.header')
    ->setMultipleConditionalClasses([
        'isStick' => 'sticky-fixed',
        'isTransparent' => 'transparent',
        'isScrolled' => 'scrolled'
    ]);
```

**Result:**

```

```

### Custom Template Expression

[](#custom-template-expression)

```
$dom->find('.button')
    ->setTemplateExpression('className', 'btn ${type === "primary" ? "btn-primary" : "btn-secondary"}');
```

**Result:**

```

```

### Convert class to className

[](#convert-class-to-classname)

```
$dom->find('div')->convertToClassName();
```

**Before:** ``
**After:** ``

---

Removing Elements
-----------------

[](#removing-elements)

### Returns: `RegexNodeCollection` (chainable)

[](#returns-regexnodecollection-chainable-2)

```
// Remove elements from DOM
$dom->find('.old-widget')->remove();
$dom->find('#deprecated')->remove();
```

---

Iteration &amp; Filtering
-------------------------

[](#iteration--filtering)

### Returns: `RegexNodeCollection` (chainable) or transformed data

[](#returns-regexnodecollection-chainable-or-transformed-data)

```
// Iterate each element
$dom->find('.item')->each(function($element, $index) {
    echo "Item $index: " . $element['html'] . "\n";
});

// Map elements (transform)
$texts = $dom->find('.item')->map(function($element, $index) {
    return strip_tags($element['html']);
});
// Returns: Collection or array

// Filter elements
$filtered = $dom->find('.item')->filter(function($element, $index) {
    return strpos($element['html'], 'active') !== false;
});
// Returns: RegexNodeCollection with filtered elements
```

---

Saving &amp; Output
-------------------

[](#saving--output)

### Various Return Types

[](#various-return-types)

```
// Get HTML as string
$html = $dom->html();

// Set HTML
$dom->setHtml($newHtmlString);
// Returns: XDOM (chainable)

// Save to file
$dom->saveToFile('/path/to/output.html');
// Returns: XDOM (chainable)

// Save to Laravel Storage
$dom->saveToStorage('public/output.html');
// Returns: XDOM (chainable)

// Return as Laravel Response
return $dom->toResponse();
// Returns: Response
// Automatically sets Content-Type: text/html
```

---

Advanced Usage - RegexHelper
----------------------------

[](#advanced-usage---regexhelper)

For direct regex operations without the fluent interface:

```
use devoashim\regxdomdocument\RegexHelper;
```

### Extract Content

[](#extract-content)

**Returns: `string` or `null`**

```
// Extract full element (with tags)
$content = RegexHelper::extractTagContent($html, 'div', 'header', 'class');
// From: Content
// Returns: "Content"

$content = RegexHelper::extractTagContent($html, 'section', 'main', 'id');
// From: Content
// Returns: "Content"

// Extract inner content (without tags)
$inner = RegexHelper::extractInnerContent($html, 'div', 'container', 'class');
// From: Text
// Returns: "Text"
```

### Replace Content

[](#replace-content)

**Returns: `string`**

```
// Replace full element
$newHtml = RegexHelper::replaceTagContent(
    $html,
    'div',
    'header',
    ''
);

// Replace inner content only
$newHtml = RegexHelper::replaceInnerContent(
    $html,
    'div',
    'content',
    ''
);
```

### Find Multiple Elements

[](#find-multiple-elements)

**Returns: `array`**

```
// Find all matching elements
$widgets = RegexHelper::findAllTags($html, 'div', 'widget', 'class');
// Returns: ['1', '2', ...]

foreach ($widgets as $i => $widget) {
    echo "Widget $i: $widget\n";
}
```

### Remove Elements

[](#remove-elements)

**Returns: `string`**

```
// Remove all matching elements
$cleanHtml = RegexHelper::removeAllTags($html, 'div', 'ads', 'class');
```

### Check Existence

[](#check-existence)

**Returns: `bool`**

```
// Check if element exists
if (RegexHelper::hasTag($html, 'div', 'header', 'class')) {
    echo "Header exists!";
}
```

### Attribute Helpers

[](#attribute-helpers)

**Returns: `array` or `string`**

```
// Extract all attributes from tag
$tag = '';
$attrs = RegexHelper::extractAttributes($tag);
// Returns: ['class' => 'box', 'id' => 'main', 'data-value' => '123']

// Replace attribute value
$newTag = RegexHelper::replaceAttribute($tag, 'class', 'new-box active');
// Returns: ''
```

### Template Literal Generation

[](#template-literal-generation-1)

**Returns: `string`**

```
// Convert to template literal
$reactHtml = RegexHelper::setDynamicClassName(
    $html,
    'div',
    'header',
    'isStick',
    'sticky-fixed'
);
```

---

Method Reference
----------------

[](#method-reference)

### XDOM Methods

[](#xdom-methods)

MethodReturnsDescription`load($html)`XDOMLoad HTML string`loadFromFile($path)`XDOMLoad from file`find($selector)`RegexNodeCollectionFind elements`html()`stringGet full HTML`setHtml($html)`XDOMSet HTML (chainable)`saveToFile($path)`XDOMSave to file (chainable)`saveToStorage($path)`XDOMSave to Laravel Storage`toResponse()`ResponseReturn as Laravel response### RegexNodeCollection Methods

[](#regexnodecollection-methods)

MethodReturnsChainableDescription`innerHTML()`stringNoGet inner HTML`outerHTML()`stringNoGet outer HTML`text()`stringNoGet text content`attr($name)`string/nullNoGet attribute value`attr($name, $value)`RegexNodeCollectionYesSet attribute`hasAttr($name)`boolNoCheck if has attribute`removeAttr($name)`RegexNodeCollectionYesRemove attribute`addClass($class)`RegexNodeCollectionYesAdd single class`addClasses($classes)`RegexNodeCollectionYesAdd multiple classes`removeClass($class)`RegexNodeCollectionYesRemove class`toggleClass($class)`RegexNodeCollectionYesToggle class`setClasses($classes)`RegexNodeCollectionYesSet all classes`hasClass($class)`boolNoCheck if has class`conditionalClass($class, $condition)`RegexNodeCollectionYesAdd class if condition true`setInnerHTML($html)`RegexNodeCollectionYesSet inner HTML`setOuterHTML($html)`RegexNodeCollectionYesReplace entire element`setText($text)`RegexNodeCollectionYesSet text (encoded)`append($html)`RegexNodeCollectionYesAppend inside element`prepend($html)`RegexNodeCollectionYesPrepend inside element`before($html)`RegexNodeCollectionYesInsert before element`after($html)`RegexNodeCollectionYesInsert after element`remove()`RegexNodeCollectionYesRemove element`setDynamicClass($var, $class)`RegexNodeCollectionYesAdd template literal`setMultipleConditionalClasses($array)`RegexNodeCollectionYesMultiple conditionals`setTemplateExpression($attr, $expr)`RegexNodeCollectionYesCustom template`convertToClassName()`RegexNodeCollectionYesclass → className`each($callback)`RegexNodeCollectionYesIterate elements`map($callback)`Collection/arrayNoTransform elements`filter($callback)`RegexNodeCollectionNoFilter elements`first()`array/nullNoGet first element`last()`array/nullNoGet last element`get($index)`array/nullNoGet by index`getMatches()`arrayNoGet all matches`count()`intNoCount elements`isEmpty()`boolNoCheck if empty`isNotEmpty()`boolNoCheck if not empty### RegexHelper Static Methods

[](#regexhelper-static-methods)

MethodReturnsDescription`extractTagContent($html, $tag, $id, $type)`string/nullExtract full element`extractInnerContent($html, $tag, $id, $type)`string/nullExtract inner content`replaceTagContent($html, $tag, $id, $new, $type)`stringReplace full element`replaceInnerContent($html, $tag, $id, $new, $type)`stringReplace inner content`findAllTags($html, $tag, $id, $type)`arrayFind all matching`removeAllTags($html, $tag, $id, $type)`stringRemove all matching`hasTag($html, $tag, $id, $type)`boolCheck if exists`extractAttributes($tag)`arrayGet all attributes`replaceAttribute($tag, $name, $value)`stringReplace attribute value`setDynamicClassName($html, $tag, $id, $var, $class)`stringCreate template literal**Note:** `$type` parameter can be `'class'` (default) or `'id'`

---

Use Cases
---------

[](#use-cases)

### 1. React Component Conversion

[](#1-react-component-conversion)

```
$dom = XDOM::loadFromFile('template.html');

$dom->find('.header')->setInnerHTML('');
$dom->find('.navigation')->setInnerHTML('');
$dom->find('.content')->setInnerHTML('');
$dom->find('.footer')->setInnerHTML('');

echo $dom->html();
```

### 2. Sticky Header with Template Literal

[](#2-sticky-header-with-template-literal)

```
$dom = XDOM::loadFromFile('index.html');

$dom->find('.stricky-header')
    ->setDynamicClass('isStick', 'stricky-fixed')
    ->attr('data-component', 'header');

echo $dom->html();
```

### 3. Dynamic Navigation

[](#3-dynamic-navigation)

```
$dom->find('.nav-item')
    ->setDynamicClass('isActive', 'active');
```

**Result:**

```

```

### Add ref attribute to element's opening tag

[](#add-ref-attribute-to-elements-opening-tag)

```
 $dom->find('.main-header')->addRef('headerRef');
```

**Before:**

```

```

**After:**

```

```

### 4. Template Variable Injection

[](#4-template-variable-injection)

```
$dom = XDOM::load($template);

$dom->find('#username')->setInnerHTML('{{user.name}}');
$dom->find('#email')->setInnerHTML('{{user.email}}');
$dom->find('#role')->setInnerHTML('{{user.role}}');

return $dom->html();
```

### 5. Batch Widget Processing

[](#5-batch-widget-processing)

```
$dom->find('.widget')
    ->addClass('active')
    ->addClass('featured')
    ->attr('data-loaded', 'true');
```

### 6. Complex Component Building

[](#6-complex-component-building)

```
$dom->find('#app')
    ->setInnerHTML('')
    ->addClass('loaded')
    ->addClass('active')
    ->attr('data-component', 'root')
    ->attr('data-version', '2.0')
    ->prepend('')
    ->append('');
```

### 7. Conditional Modifications

[](#7-conditional-modifications)

```
$element = $dom->find('#app');

if ($element->hasClass('old')) {
    $element->removeClass('old')->addClass('new');
}

if (!$element->hasAttr('data-version')) {
    $element->attr('data-version', '2.0');
}
```

### 8. Extract and Replace Sections

[](#8-extract-and-replace-sections)

```
// Extract
$header = RegexHelper::extractTagContent($html, 'div', 'header', 'class');

// Replace
$newHtml = RegexHelper::replaceTagContent(
    $html,
    'div',
    'header',
    ''
);
```

### 9. Navigation Menu Processing

[](#9-navigation-menu-processing)

```
// Find nav inside header only
$nav = $dom->find('header nav');

if ($nav->isNotEmpty()) {
    $nav->setInnerHTML('');
}
```

### 10. Multi-Step Content Wrapping

[](#10-multi-step-content-wrapping)

```
$dom->find('#content')
    ->before('')
    ->after('')
    ->addClass('inner-content');
```

---

Method Chaining Examples
------------------------

[](#method-chaining-examples)

All modification methods return `RegexNodeCollection`, enabling powerful chaining:

```
// Example 1: Complete component setup
$dom->find('#app')
    ->setInnerHTML('')
    ->addClass('loaded')
    ->addClass('active')
    ->attr('data-component', 'root')
    ->attr('data-version', '2.0')
    ->prepend('')
    ->append('');

// Example 2: Style and configure widget
$dom->find('.widget')
    ->addClass('active')
    ->addClass('featured')
    ->attr('data-priority', 'high')
    ->setInnerHTML('');

// Example 3: Update card styling
$dom->find('.card')
    ->removeClass('old-style')
    ->addClass('new-style')
    ->attr('data-updated', 'true')
    ->setInnerHTML('');
```

---

Key Features
------------

[](#key-features)

**Exact Content Preservation** - No HTML encoding or modification
**React/Vue/JSX Support** - Perfect for component templates
**Template Literals** - Generate dynamic className with conditionals
**Template Variables** - Works with {{mustache}}, {blade}, etc.
**Pure Regex** - Fast, lightweight, no dependencies
**Method Chaining** - Clean, readable code
**Laravel Integration** - Storage and Response helpers
**No DOM Parser** - Preserves exact formatting and structure

---

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

License
-------

[](#license)

This project is licensed under the MIT License.

Credits
-------

[](#credits)

Created by [devoashim](https://github.com/devoashim)

Support
-------

[](#support)

- **GitHub Issues:** [Create an issue](https://github.com/devoashim/regx-domdocument/issues)
- **Documentation:** Full API reference and examples included

⭐ Star Us!
----------

[](#-star-us)

If you find this package useful, please consider giving it a star on GitHub!

---

**Remember:**

- All content is preserved EXACTLY (no encoding)
- Perfect for React/Vue/Angular components
- Works seamlessly with template variables
- Pure regex - fast and lightweight
- Method chaining for clean, maintainable code

---

*Last Updated: 2024**Version: Complete Merged Guide*

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance79

Regular maintenance activity

Popularity3

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~0 days

Total

3

Last Release

112d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/dfcef9068118a5538709ef5d8fec79a44a7b4c17716b93d4d1a09b88705721a2?d=identicon)[DevOashim](/maintainers/DevOashim)

---

Top Contributors

[![DevOashim](https://avatars.githubusercontent.com/u/179505619?v=4)](https://github.com/DevOashim "DevOashim (5 commits)")

---

Tags

laravelparsermanipulationhtmldomregexreactjsxtemplate-literal

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/devoashim-regxdomdocument/health.svg)

```
[![Health](https://phpackages.com/badges/devoashim-regxdomdocument/health.svg)](https://phpackages.com/packages/devoashim-regxdomdocument)
```

###  Alternatives

[paquettg/php-html-parser

An HTML DOM parser. It allows you to manipulate HTML. Find tags on an HTML page with selectors just like jQuery.

2.4k7.9M123](/packages/paquettg-php-html-parser)[simplehtmldom/simplehtmldom

A fast, simple and reliable HTML document parser for PHP.

1921.3M14](/packages/simplehtmldom-simplehtmldom)[oscarotero/html-parser

Parse html strings to DOMDocument

165.0M1](/packages/oscarotero-html-parser)

PHPackages © 2026

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