<?php
$pattern = '/(?:src|href)\=(?:\\\'|")([^\\\'"]+)(?:\\\'|")/';
$source = <<<SRC
<a href="http://www.sape.ru">some text</a>
<img src='logo.jpg' alt=''></a>
<img src='../../logo.jpg' alt=''></a>
<img src='/path/to/file' alt=''></a>
SRC;
$baseUrl = 'www.sape.ru';
$callback = function($matches) use ($baseUrl) {
$srcTag = $matches[0];
$url = $matches[1];
$search = array(
'http://',
'https://',
'../',
'./',
'//',
$baseUrl
);
$url = str_replace($search, '', $url);
$url = preg_replace('/^[^\/]\//', '/', $url);
$path = parse_url($url, PHP_URL_PATH);
//if (empty($path)) {
// $path = '/';
//}
$query = parse_url($url, PHP_URL_QUERY);
if (!empty($query)) {
$path.= '?' . $query;
}
$fragment = parse_url($url, PHP_URL_FRAGMENT);
if (!empty($fragment)) {
$path.= '#' . $fragment;
}
$resultUrl = 'http://' . $baseUrl . '/' . ltrim($path, '/');
var_dump($resultUrl);
return $resultUrl;
};
preg_replace_callback($pattern, $callback, $source);
preferences:
27.31 ms | 402 KiB | 5 Q