2017 © Pedro Peláez
 

library url-finder

Find and replace URLs in HTML and CSS documents

image

timostamm/url-finder

Find and replace URLs in HTML and CSS documents

  • Friday, January 12, 2018
  • by timostamm
  • Repository
  • 1 Watchers
  • 1 Stars
  • 42 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 0 Forks
  • 0 Open issues
  • 1 Versions
  • 17 % Grown

The README.md

PHP URL Finder

Build Status, (*1)

Find and replace URLs in HTML, CSS and Markdown documents., (*2)

Example input HTML:, (*3)

<html>
<body>
  <img src="http://domain.tld/img/a.jpg" >
  <div style="background-image: url(./c.jpg);"></div>
  <style>
    .bg-img { background-image: url(../images/h.jpg); }
  </style>
  <script src="https://cdn.tld/angular.min.js"></script>
  <link rel="stylesheet" type="text/css" href="/styles/f.css" />
  ...

Find all jpegs on our domain and move them to /images/, (*4)

$documentUrl = 'http://domain.tld/products/all.html';
$finder = UrlFinder::create($html, $documentUrl);

foreach ($finder->find('*domain.tld/*.jpg') as $url) {
  $newpath = '/images/' . $url->path->filename();
  $url
    ->replacePath($newpath)
    ->makeAbsolute()
    ->clearHost();
}

$finder->getDocument(); // returns the updated HTML string

The result:, (*5)

<html>
<body>
  <img src="/images/a.jpg" >
  <div style="background-image: url(/images/c.jpg);"></div>
  <style>
    .bg-img { background-image: url(/images/h.jpg); }
  </style>
  <script src="https://cdn.tld/angular.min.js"></script>
  <link rel="stylesheet" type="text/css" href="/styles/f.css" />
  ...

The UrlFinder takes care of proper quoting of URLs in attributes, url-notations in style-attributes and url- notation within style-tags., (*6)

Using the fluid collection interface:, (*7)

$urls = $finder
  ->find('*') // matches the entire absolute URL
  ->matchHost('*')
  ->matchPath('*')
  ->onlyHttps()
  ->matchFilenameNot('*.less');
  // etc.

$urls->count();
$urls->toArray();
$urls->first();
foreach($urls as $url) {}

Updating URLs:, (*8)

$url->query->set('text', 'value');
$url->clear( Url::CREDENTIALS );

See https://github.com/timostamm/url-builder for documentation of the URL object., (*9)

Finding URLs in CSS works exactly the same:, (*10)

$finder = UrlFinder::create($css, 'http://domain.tld/styles/main.css');
$finder->find()->first()->makeAbsolute();
$finder->getDocument();

Please note that import statements are not suported and you have to follow stylesheet-links yourself., (*11)

Markdown support

Markdown support is experimental right now. Caveats:, (*12)

  • Link / image titles are not supported and will raise an error
  • HTML with links within markdown is ignored
  • Markdown is not available using UrlFinder::create, use new MarkdownUrlFinder()

The Versions

12/01 2018

dev-master

9999999-dev

Find and replace URLs in HTML and CSS documents

  Sources   Download

AGPL-3.0

The Requires

 

The Development Requires

css html url-replace