timostamm / url-finder
在HTML和CSS文档中查找并替换URL
v1.0.2
2020-09-28 09:20 UTC
Requires
- php: >=5.6
- timostamm/pathinfo: ^1.0.1
- timostamm/url-builder: ^1.0.1
Requires (Dev)
- phpunit/phpunit: ^9.3
This package is auto-updated.
Last update: 2024-08-28 17:53:59 UTC
README
在HTML、CSS和Markdown文档中查找并替换URL。
示例输入HTML
<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" /> ...
查找我们域名下的所有jpeg文件并将它们移动到/images/
$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
结果
<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" /> ...
UrlFinder负责在属性中正确引用URL,在样式属性中的url标记以及在样式标签内的url标记。
使用流集合接口
$urls = $finder ->find('*') // matches the entire absolute URL ->matchHost('*') ->matchPath('*') ->onlyHttps() ->matchFilenameNot('*.less'); // etc. $urls->count(); $urls->toArray(); $urls->first(); foreach($urls as $url) {}
更新URL
$url->query->set('text', 'value'); $url->clear( Url::CREDENTIALS );
有关URL对象的文档,请参阅https://github.com/timostamm/url-builder
CSS中的URL查找与此完全相同
$finder = UrlFinder::create($css, 'http://domain.tld/styles/main.css'); $finder->find()->first()->makeAbsolute(); $finder->getDocument();
请注意,导入语句不受支持,您必须自行遵循样式表链接。
Markdown支持
Markdown支持目前处于实验阶段。注意事项
- 不支持链接/图片标题,将会引发错误
- Markdown中的链接HTML将被忽略
- 不使用UrlFinder::create获取Markdown,请使用new MarkdownUrlFinder()