How to replace urls with regex php

I have a text file in which I have many urls like http://96.156.138.108/i/01/00382/gbixtksl4n0p0000.jpg#xywh=0,0,108,60

I want to change all urls with my urls http://testing.to/testing/vtt/vt1.vtt#xywh=0,0,108,60

I use this regex

$result = preg_replace('"\b(https?://\S+)"', 'http://testing.to/testing/vtt/vt1.vtt', $result);

but its not working well its changing the whole url

from this http://96.156.138.108/i/01/00382/gbixtksl4n0p0000.jpg#xywh=0,0,108,60

to that http://testing.to/testing/vtt/vt1.vtt

I want to change only the url except # xywh == 0,0,108,60 , like this

http://testing.to/testing/vtt/vt1.vtt#xywh==0,0,108,60

+4
source share
5 answers

You can use [^\s#]instead of \Smatching only non-spaces, not #characters:

$result = preg_replace(
    '"\bhttps?://[^\s#]+"',
    'http://testing.to/testing/vtt/vt1.vtt',
    $result
);
+2
source

Try the following:

$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);
+1
source

preg_replace , URL-,
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;

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
+1

explode()

$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];
0
$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);

$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);
0

Source: https://habr.com/ru/post/1620507/


All Articles