PHPackages                             klkvsk/clearurls - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. klkvsk/clearurls

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

klkvsk/clearurls
================

High-performance PHP library for removing tracking parameters from URLs using ClearURLs ruleset

1.0.20251126(5mo ago)00MITPHPPHP &gt;=8.3CI passing

Since Nov 26Pushed 5mo agoCompare

[ Source](https://github.com/klkvsk/clearurls-php)[ Packagist](https://packagist.org/packages/klkvsk/clearurls)[ Docs](https://github.com/klkvsk/clearurls-php)[ RSS](/packages/klkvsk-clearurls/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (1)Versions (2)Used By (0)

ClearUrls PHP
=============

[](#clearurls-php)

High-performance PHP library for removing tracking parameters from URLs using the [ClearURLs](https://github.com/ClearURLs/Addon) ruleset.

Features
--------

[](#features)

- 🚀 **Fast** - Optimized for bulk URL cleaning with pre-compiled regex patterns
- 🎯 **Zero Dependencies** - Pure PHP 8.3+ standard library only
- 🔄 **Auto-updating Rules** - Fetches latest rules from ClearURLs project
- 🧪 **Well Tested** - Comprehensive test suite with performance benchmarks
- 💪 **Production Ready** - Battle-tested rules from the ClearURLs community
- 📦 **Easy Integration** - Simple, one-function API

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

[](#installation)

### Requirements

[](#requirements)

- PHP 8.3 or higher
- Composer

### Using Composer

[](#using-composer)

```
composer require klkvsk/clearurls
```

The package includes pre-compiled rules (src/Rules.php), so it's ready to use immediately after installation.

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

[](#quick-start)

```
use ClearUrls\ClearUrls;

// Create cleaner with default rules
$cleaner = ClearUrls::createDefault();

// Clean a URL
$result = $cleaner->clean('https://example.com/page?utm_source=twitter&id=123');

echo $result->url; // https://example.com/page?id=123
echo $result->wasModified ? 'Modified' : 'Unchanged'; // Modified
```

Usage Examples
--------------

[](#usage-examples)

### Basic URL Cleaning

[](#basic-url-cleaning)

```
$cleaner = ClearUrls::createDefault();

// Remove UTM parameters
$result = $cleaner->clean(
    'https://example.com/page?utm_source=twitter&utm_medium=social&id=123'
);
echo $result->url; // https://example.com/page?id=123

// Remove Facebook tracking
$result = $cleaner->clean(
    'https://example.com/page?fbclid=abc123&id=456'
);
echo $result->url; // https://example.com/page?id=456

// Remove Google tracking
$result = $cleaner->clean(
    'https://www.google.com/search?q=test&ved=123&ei=456'
);
echo $result->url; // https://www.google.com/search?q=test
```

### Handling Redirections

[](#handling-redirections)

```
$cleaner = ClearUrls::createDefault();

// Extract target URL from Google redirect
$result = $cleaner->clean(
    'https://www.google.com/url?q=https://example.com/target&ved=123'
);
echo $result->url; // https://example.com/target
echo $result->wasRedirected ? 'Yes' : 'No'; // Yes

// Extract target URL from Facebook redirect
$result = $cleaner->clean(
    'https://l.facebook.com/l.php?u=https%3A%2F%2Fexample.com%2Fpage&h=abc'
);
echo $result->url; // https://example.com/page
```

### Referral Marketing

[](#referral-marketing)

By default, referral marketing parameters (like Amazon affiliate tags) are removed. To keep them:

```
$cleaner = ClearUrls::createDefault(allowReferralMarketing: true);

$result = $cleaner->clean(
    'https://www.amazon.com/dp/B08ABC123?tag=myaffiliate-20&ref=nav'
);
// With allowReferralMarketing=true: keeps 'tag' parameter
// With allowReferralMarketing=false: removes 'tag' parameter
```

### Checking Result Status

[](#checking-result-status)

```
$result = $cleaner->clean($url);

if ($result->wasModified) {
    echo "Removed tracking parameters\n";
}

if ($result->wasRedirected) {
    echo "Extracted target URL from redirect\n";
}

if ($result->wasBlocked) {
    echo "URL was blocked (completeProvider rule)\n";
}

if ($result->hadAnyAction()) {
    echo "Something was changed\n";
}
```

### Batch Processing

[](#batch-processing)

```
$cleaner = ClearUrls::createDefault();

$urls = [
    'https://example.com/page1?utm_source=email',
    'https://example.com/page2?fbclid=abc123',
    'https://example.com/page3?gclid=xyz789',
];

foreach ($urls as $url) {
    $result = $cleaner->clean($url);
    echo "{$url} -> {$result->url}\n";
}
```

### Custom Configuration

[](#custom-configuration)

If you need custom rules, you can create providers manually:

```
use ClearUrls\ClearUrls;
use ClearUrls\Provider;

$providers = [
    new Provider(
        name: 'custom',
        urlPattern: '#^https?://example\.com#i',
        completeProvider: false,
        rules: [
            '#^tracking$#i',
            '#^session_id$#i',
        ],
        rawRules: [],
        referralMarketing: [],
        exceptions: [],
        redirections: [],
        forceRedirection: false
    ),
];

$cleaner = new ClearUrls($providers);
```

Performance
-----------

[](#performance)

The library is optimized for speed:

- Pre-compiled regex patterns (no runtime compilation)
- Efficient URL parsing and rebuilding
- Minimal memory usage
- Suitable for bulk URL cleaning operations

Run performance benchmarks:

```
vendor/bin/phpunit tests/PerformanceTest.php --verbose
```

Architecture
------------

[](#architecture)

### Core Components

[](#core-components)

1. **ClearUrls.php** - Main cleaning logic

    - URL parsing and validation
    - Provider matching
    - Rule application
    - URL rebuilding
2. **Provider.php** - Rule provider data structure

    - Pattern matching
    - Exception handling
    - Redirection extraction
3. **ClearUrlResult.php** - Immutable result object

    - Cleaned URL
    - Modification status
    - Action flags
4. **Rules.php** - Auto-generated (205 providers, 734+ rules)

    - Pre-compiled regex patterns
    - Optimized data structure
    - Generated by build script

### Build System (For Package Maintainers)

[](#build-system-for-package-maintainers)

**compile-rules.php** - Rules compilation script (used by package maintainers to update rules)

- Fetches from
- Compiles all regex patterns
- Generates optimized PHP code (src/Rules.php)
- Caches rules locally for offline builds with `--local` flag

How It Works
------------

[](#how-it-works)

1. **Build Time** (package maintainers only): The build script fetches rules from ClearURLs and compiles them to PHP with pre-compiled regex patterns
2. **Runtime** (end users): When cleaning a URL:
    - Finds matching provider by URL pattern
    - Checks exceptions (URLs that should not be processed)
    - Handles redirections (extracts embedded URLs)
    - Applies raw rules (regex on entire URL)
    - Removes matching query parameters and fragments
    - Rebuilds the clean URL

Rules Format
------------

[](#rules-format)

Rules are fetched from the ClearURLs project. Each provider has:

- `urlPattern`: Regex to match URLs
- `completeProvider`: Block entire provider
- `rules`: Query/fragment parameters to remove
- `rawRules`: Regex patterns to apply to entire URL
- `referralMarketing`: Optional marketing parameters
- `exceptions`: URLs to skip
- `redirections`: Extract embedded URLs
- `forceRedirection`: Force redirect behavior

See [ClearURLs documentation](https://docs.clearurls.xyz/latest/specs/rules/) for details.

Updating Rules (For Package Maintainers)
----------------------------------------

[](#updating-rules-for-package-maintainers)

The pre-compiled rules (src/Rules.php) are included in the package. End users don't need to update them.

**For package maintainers**: To update rules to the latest version from ClearURLs:

```
php build/compile-rules.php
```

This fetches rules from  and regenerates src/Rules.php.

The build script compares the SHA-256 hash of fetched rules against the previous version:

- **Rules changed**: Updates `updatedAt` timestamp in metadata → triggers new release
- **Rules unchanged**: Preserves existing `updatedAt` timestamp → no new release

Use the `--local` flag to skip fetching and compile from cached rules:

```
php build/compile-rules.php --local
```

### Automated Rules Updates (GitHub Actions)

[](#automated-rules-updates-github-actions)

The repository includes a GitHub Actions workflow that automatically:

1. Fetches the latest ClearURLs rules
2. Compiles them to optimized PHP code
3. Creates a new versioned release (format: `1.0.YYYYMMDD`)
4. Updates the CHANGELOG
5. Pushes to GitHub and creates a git tag for Packagist

**To trigger an update:**

1. Go to the repository's "Actions" tab on GitHub
2. Select "Update ClearURLs Rules" workflow
3. Click "Run workflow" button
4. The workflow fetches rules and checks if they changed (via SHA-256 hash)
5. If rules changed AND version tag doesn't exist → creates new release
6. If rules unchanged → keeps existing version, no duplicate release

**Version format:** `x.y.YYYYMMDD` where:

- `x.y` = Major.Minor version (update manually when adding code features)
- `YYYYMMDD` = Date when rules were fetched from ClearURLs

This ensures Packagist automatically picks up new rule updates without manual intervention.

Project Structure
-----------------

[](#project-structure)

```
clearurls-php/
├── src/
│   ├── ClearUrls.php          # Main library class
│   ├── Provider.php           # Provider data structure
│   ├── ClearUrlResult.php     # Result object
│   └── Rules.php              # Auto-generated rules
├── build/
│   ├── compile-rules.php      # Build script
│   └── data.min.json          # Cached rules (git-ignored)
├── tests/
│   ├── ClearUrlsTest.php      # Unit tests
│   └── PerformanceTest.php    # Benchmarks
├── examples/
│   ├── basic_usage.php        # Simple examples
│   └── advanced_usage.php     # Advanced features
├── composer.json
├── phpunit.xml
└── README.md

```

Testing
-------

[](#testing)

Install dev dependencies:

```
composer install --dev
```

Run tests:

```
# All tests
vendor/bin/phpunit

# Specific test file
vendor/bin/phpunit tests/ClearUrlsTest.php

# Performance benchmarks
vendor/bin/phpunit tests/PerformanceTest.php --verbose
```

Supported Providers (205 total)
-------------------------------

[](#supported-providers-205-total)

### Major Providers

[](#major-providers)

- Google (search, ads, redirects)
- Amazon (products, search, ads)
- Facebook (posts, redirects)
- YouTube (videos, tracking)
- Twitter/X (posts, tracking)
- LinkedIn (profiles, tracking)
- Reddit (posts, redirects)
- Instagram (posts, tracking)
- TikTok (videos, tracking)
- And 196+ more...

### Global Rules

[](#global-rules)

- UTM parameters (utm\_source, utm\_medium, etc.)
- Facebook tracking (fbclid)
- Google tracking (gclid, \_ga)
- And many more tracking parameters

API Reference
-------------

[](#api-reference)

### ClearUrls Class

[](#clearurls-class)

```
// Create with default rules
$cleaner = ClearUrls::createDefault(bool $allowReferralMarketing = false): self

// Create with custom providers
$cleaner = new ClearUrls(array $providers, bool $allowReferralMarketing = false)

// Clean a URL
$result = $cleaner->clean(string $url): ClearUrlResult

// Set referral marketing preference
$cleaner->setAllowReferralMarketing(bool $allow): void
```

### ClearUrlResult Class

[](#clearurlresult-class)

```
readonly class ClearUrlResult {
    public string $url;              // Cleaned URL
    public bool $wasModified;        // Was URL modified?
    public bool $wasBlocked;         // Was URL blocked?
    public bool $wasRedirected;      // Was URL redirected?

    public function hadAnyAction(): bool;  // Any action taken?
}
```

### Provider Class

[](#provider-class)

```
readonly class Provider {
    public function __construct(
        public string $name,
        public string $urlPattern,
        public bool $completeProvider,
        public array $rules,
        public array $rawRules,
        public array $referralMarketing,
        public array $exceptions,
        public array $redirections,
        public bool $forceRedirection
    );

    public function matchesUrl(string $url): bool;
    public function getRedirection(string $url): ?string;
    public function getAllRules(bool $includeReferralMarketing): array;
}
```

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

[](#contributing)

Contributions are welcome! Areas for contribution:

- Performance optimizations
- Additional test cases
- Documentation improvements
- Bug fixes
- Feature requests

Credits
-------

[](#credits)

- **Original Project**: [ClearURLs by KevinRoebert](https://github.com/ClearURLs/Addon)
- **Rules**: Maintained by ClearURLs community
- **PHP Implementation**: klkvsk

License
-------

[](#license)

MIT License

The rules data is provided by the [ClearURLs project](https://github.com/ClearURLs/Addon) and is licensed under LGPL-3.0-or-later.

Links
-----

[](#links)

- **GitHub**:
- **Packagist**:
- **ClearURLs Docs**:
- **Issue Tracker**:

###  Health Score

35

—

LowBetter than 79% of packages

Maintenance76

Regular maintenance activity

Popularity0

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 75% 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

Unknown

Total

1

Last Release

164d ago

### Community

Maintainers

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

---

Top Contributors

[![klkvsk](https://avatars.githubusercontent.com/u/1466771?v=4)](https://github.com/klkvsk "klkvsk (3 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (1 commits)")

---

Tags

urltrackingcleanerUTMprivacycleanurlclearurlclearurlscleanurls

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/klkvsk-clearurls/health.svg)

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

###  Alternatives

[spatie/url

Parse, build and manipulate URL's

73914.3M97](/packages/spatie-url)[jbroadway/urlify

A fast PHP slug generator and transliteration library that converts non-ascii characters for use in URLs.

6737.4M62](/packages/jbroadway-urlify)[league/uri-components

URI components manipulation library

31932.3M66](/packages/league-uri-components)[sabre/uri

Functions for making sense out of URIs.

29335.2M40](/packages/sabre-uri)[spomky-labs/base64url

Base 64 URL Safe Encoding/Decoding PHP Library

15439.5M49](/packages/spomky-labs-base64url)[misd/linkify

Converts URLs and email addresses in text into HTML links

1122.9M10](/packages/misd-linkify)

PHPackages © 2026

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