I have several html files with img tags and absolute image paths. I want to remove the absolute part and just leave a relative path.
Eg. http://domain1.com/media/uploads/2017/11/image-test-1.jpg https://domain2.org/photos/uploads/2016/08/anotherimage.png
Those two would end up like this:
images/image-test-1.jpg images/anotherimage.png
How can I accomplish this?
This is what I currently have: preg_replace( "@(http[s]*?://[-\\w\\.]+)(\\/\\w+\\.(png|jpg))@", 'images/$2', $url );
It was returning everything up to the uploads dir, but, after some tweaks it doesn't work at all...
My pattern will match from http
to the last /
in the url and replace it with images/
.
Code: ( Demo )
$urls=[
'http://domain1.com/media/uploads/2017/11/image-test-1.jpg',
'https://domain2.org/photos/uploads/2016/08/anotherimage.png'
];
$urls=preg_replace('~https?://(?:[^/]*/)*~','images/',$urls);
var_export($urls);
Output:
array (
0 => 'images/image-test-1.jpg',
1 => 'images/anotherimage.png',
)
Pattern Explanation:
~ #Pattern delimiter
https?:// #Match http:// or https://
(?: #Start non-capturing group
[^/]* #Match zero or more non-slash characters
/ #Match slash
) #End non-capturing group
* #Match zero or more occurrences of the non-capturing group
~ #Pattern delimiter
Here is a pattern demo . *note, I had to add \\s
to the negated character class to make it match multiple urls in one string.
As for your pattern:
@
( #this generates capture group number 1
http
[s]*? #simpler would be: s?
://
[-\w\.]+ #dot doesn't need escaping; this will match [-A-Za-z0-9_.]
)
( #this generates capture group number 2
\/ #escaping is not necessary, just use: /
\w+ #this will match one or more of [A-Za-z0-9_]
\. #this will match literal dot
(png|jpg) #this generates capture group number 3 containing png or jpg
)
@
To repair your pattern: ( Demo )
/
to change [-\\w.]
to this: [-\\w./]
\\w+
to [\\w-]+
images$2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.