如何使用regex php替换URL
我有一个文本文件,其中有许多类似这样的URL如何使用regex php替换URL,php,regex,Php,Regex,我有一个文本文件,其中有许多类似这样的URLhttp://96.156.138.108/i/01/00382/gbixtksl4n0p0000.jpg#xywh=0,0108,60 我想用我的URL更改所有URL,如下http://testing.to/testing/vtt/vt1.vtt#xywh=0,0108,60 我正在使用这个正则表达式 $result = preg_replace('"\b(https?://\S+)"', 'http://testing.to/testing/vtt
http://96.156.138.108/i/01/00382/gbixtksl4n0p0000.jpg#xywh=0,0108,60
我想用我的URL更改所有URL,如下http://testing.to/testing/vtt/vt1.vtt#xywh=0,0108,60
我正在使用这个正则表达式
$result = preg_replace('"\b(https?://\S+)"', 'http://testing.to/testing/vtt/vt1.vtt', $result);
但它的工作不好,它改变了整个url
从此http://96.156.138.108/i/01/00382/gbixtksl4n0p0000.jpg#xywh=0,0108,60
对此http://testing.to/testing/vtt/vt1.vtt
我只想像这样更改url,除了#xywh==0,0108,60
您可以使用[^\s#]
而不是\s
来仅匹配非空格、非
字符:
$result = preg_replace(
'"\bhttps?://[^\s#]+"',
'http://testing.to/testing/vtt/vt1.vtt',
$result
);
这可以通过简单的explode()函数完成 试试这个:
$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);
或
虽然
preg\u replace
很好,但是有一个内置的解析URL的函数,即 将输出
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
考虑到可以更改
xywh
:$urlParts=explode(“#“,$url”)$新网址=”http://testing.to/testing/vtt/vt1.vtt#";代码>http?
应该是https?
。更正它应该是https?
。。。Thanksi还想获取旧的urlhttp://96.156.138.108/i/01/00382/gbixtksl4n0p0000.jpg
从文件到我的变量我应该做什么do@ZealSol,使用相同的模式:preg_match(“\bhttps?://[^\s#]+”,$result,$matches);打印(匹配项)代码>
$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);
$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