Reputation: 43
i have a text file in which i have many urls like this http://96.156.138.108/i/01/00382/gbixtksl4n0p0000.jpg#xywh=0,0,108,60
i want to change all urls with my urls like this http://testing.to/testing/vtt/vt1.vtt#xywh=0,0,108,60
i am using this regex
$result = preg_replace('"\b(https?://\S+)"', 'http://testing.to/testing/vtt/vt1.vtt', $result);
but its not working good its change whole url
from this http://96.156.138.108/i/01/00382/gbixtksl4n0p0000.jpg#xywh=0,0,108,60
to this http://testing.to/testing/vtt/vt1.vtt
i want to change only url except #xywh==0,0,108,60 like this
Upvotes: 4
Views: 70
Reputation: 1436
Try This:
$sourcestring="http://96.156.138.108/i/01/00382/gbixtksl4n0p0000.jpg#xywh=0,0,108,60";
echo preg_replace('/https?:\/\/.*?#/is','http://testing.to/testing/vtt/vt1.vtt#',$sourcestring);
Upvotes: 1
Reputation: 7283
Although preg_replace
is good and all, there is a built in function for parsing urls,
namely parse_url
$url = 'http://96.156.138.108/i/01/00382/gbixtksl4n0p0000.jpg#xywh=0,0,108,60';
$components = parse_url($url);
print_r($components);
$fixed = 'http://testing.to/testing/vtt/vt1.vtt#' . $components['fragment'];
print $fixed . PHP_EOL;
Will output
Array
(
[scheme] => http
[host] => 96.156.138.108
[path] => /i/01/00382/gbixtksl4n0p0000.jpg
[fragment] => xywh=0,0,108,60
)
http://testing.to/testing/vtt/vt1.vtt#xywh=0,0,108,60
Upvotes: 1
Reputation: 1138
$re = "/(.*)#(.*)/";
$str = "http://96.156.138.108/i/01/00382/gbixtksl4n0p0000.jpg#xywh=0,0,108,60";
$subst = "http://testing.to/testing/vtt/vt1.vtt#$2";
$result = preg_replace($re, $subst, $str);
OR
$re = "/(http?:.*)#(.*)/";
$str = "http://96.156.138.108/i/01/00382/gbixtksl4n0p0000.jpg#xywh=0,0,108,60";
$subst = "http://testing.to/testing/vtt/vt1.vtt#$2";
$result = preg_replace($re, $subst, $str);
Upvotes: 0
Reputation: 544
It could be done with simple explode() function
$url = "http://96.156.138.108/i/01/00382/gbixtksl4n0p0000.jpg#xywh=0,0,108,60";
$urlParts = explode("=", $url);
$newUrl = "http://testing.to/testing/vtt/vt1.vtt#xywh=";
$newUrl += $urlParts[1];
Upvotes: 0
Reputation: 368944
You can use [^\s#]
instead of \S
to match only non-spaces, non-#
characters:
$result = preg_replace(
'"\bhttps?://[^\s#]+"',
'http://testing.to/testing/vtt/vt1.vtt',
$result
);
Upvotes: 2