如何使用正则表达式php

时间:2015-12-17 08:47:49

标签: php regex

我有一个文本文件,其中有很多这样的网址http://96.156.138.108/i/01/00382/gbixtksl4n0p0000.jpg#xywh=0,0,108,60

我想用我的网址更改所有网址,例如http://testing.to/testing/vtt/vt1.vtt#xywh=0,0,108,60

我正在使用这个正则表达式

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

但它改变整个网址的效果不佳

来自此http://96.156.138.108/i/01/00382/gbixtksl4n0p0000.jpg#xywh=0,0,108,60

到此http://testing.to/testing/vtt/vt1.vtt

我想只更改#xywh == 0,0,108,60 这样的网址

  

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

5 个答案:

答案 0 :(得分:2)

您可以使用ResultSet代替[^\s#]来匹配非空格,非\S字符:

#

答案 1 :(得分:1)

试试这个:

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

答案 2 :(得分:1)

虽然preg_replace很好,但是有一个用于解析网址的内置函数,
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

答案 3 :(得分:0)

可以使用简单的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];

答案 4 :(得分: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);

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