如何preg_replace链接,以便保留哈希

时间:2016-06-29 21:43:21

标签: php regex preg-replace

我拥有动态制作的巨大在线php文件集。 它有链接,甚至一些带引号的无效链接(用首页制作)

index2.php?page=xd
index2.php?page=xj asdfa
index2.php?page=xj%20aas
index2.php?page=xj#jumpword
index2.php?page=gj#jumpword with spaces that arenot%20
index2.php?page=afdsdj#jumpword%20with
index2.php?page=xj#jumpword with "quotes" iknow


$input_lines=preg_replace("/(index2.php?page\=.*)(#[a-zA-Z0-9_ \\"]*)(\"\>)/U", "$0 --> $2", $input_lines);

我希望所有这些只是#-part而没有index2.php?page = * part。

整个晚上我都无法工作。所以请帮忙。

1 个答案:

答案 0 :(得分:0)

在某些情况下,您可以使用parse_url从网址获取属性(例如:#之后的内容),如下所示:

$urls = array(
    'index2.php?page=xd',
    'index2.php?page=xj asdfa',
    'index2.php?page=xj%20aas',
    'index2.php?page=xj#jumpword',
    'index2.php?page=gj#jumpword with spaces that arenot%20',
    'index2.php?page=afdsdj#jumpword%20with',
    'index2.php?page=xj#jumpword with "quotes" iknow',
    );

foreach($urls as $url){
    echo 'For "' . $url . '": ';
    $parsed = parse_url($url);
    echo isset($parsed['fragment']) ? $parsed['fragment'] : 'DID NOT WORK';
    echo '<br>';
}

输出:

  

对于“index2.php?page = xd”:DID NOT WORK

     

对于“index2.php?page = xj asdfa”:DID NOT WORK

     

对于“index2.php?page = xj%20aas”:DID NOT WORK

     

对于“index2.php?page = xj #jackword”:jumpword

     

对于“index2.php?page = gj#jumpword with spaces not not percent 20”:jumpword with spaces notnot%20

     

对于“index2.php?page = afdsdj #jackword%20with”:jumpword%20with

     

对于“index2.php?page = xj#jumpword with”quotes“iknow”:jumpword with“quotes”iknow