Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php preg_替换如何更改uri的一部分_Php_Regex_Preg Replace - Fatal编程技术网

Php preg_替换如何更改uri的一部分

Php preg_替换如何更改uri的一部分,php,regex,preg-replace,Php,Regex,Preg Replace,我试图用php preg_替换来更改html的所有链接。 所有URI都具有以下形式 http://example.com/page/58977?forum=60534#comment-60534 我想将其更改为: http://example.com/60534 这意味着删除“page”之后和“comment-”之前的所有内容,包括这两个字符串 我尝试了以下操作,但未返回任何更改: $result = preg_replace("/^.page.*.comment-.$/", "", $ht

我试图用php preg_替换来更改html的所有链接。 所有URI都具有以下形式

http://example.com/page/58977?forum=60534#comment-60534
我想将其更改为:

http://example.com/60534
这意味着删除“page”之后和“comment-”之前的所有内容,包括这两个字符串

我尝试了以下操作,但未返回任何更改:

$result = preg_replace("/^.page.*.comment-.$/", "", $html);
但是我的正则表达式语法似乎不正确,因为它返回的html没有改变。
你能帮我一下吗?

这个
^
是一个只匹配字符串开头的锚点,
$
只匹配字符串结尾的锚点。为了匹配,不应锚定正则表达式:

$result = preg_replace("/page.*?comment-/", "", $html);   

请注意,这可能与非URL的内容相匹配。您可能希望更具体地说明要替换的内容,例如,您可能只希望替换以
http:
https:
开头且不包含空格的链接。

您可能只需要以下内容:
此函数解析URL并返回一个关联数组,该数组包含URL中存在的任何不同组件。

不使用正则表达式的替代方法

使用
解析url()



演示:

仅当字符串本身包含URL时才起作用,如果必须替换多次出现的URL,则不起作用。我有一个带有标题的URL列表。有点像档案馆。你的密码对我来说很完美。非常感谢。
<?php    
    $url = 'http://example.com/page/58977?forum=60534#comment-60534';
    $array = parse_url($url);
    parse_str($array['query'], $query);   
    $http = ($array['scheme']) ? $array['scheme'].'://' : NULL;    
    echo $http.$array['host'].'/'.$query['forum'];
?>