正则表达式preg替换省略一个字符

时间:2014-06-19 08:34:54

标签: regex preg-replace

我使用此函数用绝对值替换相对链接,并将它们作为页面的参数,以使用file_get_contents对其进行流式处理。我认为在我的正则表达式中存在一个省略字符的问题 它的功能

$pattern = "/<a([^>]*) " .
         "href=\"[^http|ftp|https|mailto]([^\"]*)\"/";
$replace = "<a\${1} href=\"?u=" . $base . "\${2}\"";
$text = preg_replace($pattern, $replace, $text);
$pattern = "/<a([^>]*) " .
         "href='[^http|ftp|https|mailto]([^\']*)'/";

$replace = "<a\${1} href=\"?u=" . $base . "\${2}\"";
$text = preg_replace($pattern, $replace, $text);
$pattern = "/<img([^>]*) " . 
         "src=\"[^http|ftp|https]([^\"]*)\"/";
$replace = "<img\${1} src=\"" . $base . "\${2}\"";
$text = preg_replace($pattern, $replace, $text);

$pattern = "/<a([^>]*) " .
         "href=\"([^\"]*)\"/";
$replace = "<a\${1} href=\"?u=" . "\${2}\"";
$text = preg_replace($pattern, $replace, $text);

所以

 "UsersList.aspx?dir=09" 

使用此$ base url&#34;:

 http://www.some-url.com/Members/  

应该替换为

 "?u=http://www.some-url.com/Members/UsersList.aspx?dir=09"

但是我得到了

 "?u=http://www.some-url.com/Members/sersList.aspx?dir=09"

我不知道我的正则表达式中的问题以及如何解决它

1 个答案:

答案 0 :(得分:0)

Guess your a tag is like 

<a href="UsersList.aspx?dir=09"></a>

并且它不适用于此模式以获得所需的结果。

$pattern = "/<a([^>]*) " . "href=\"[^http|ftp|https|mailto]([^\"]*)\"/";

在那

[^ http | ftp | https | mailto] - 此表达式只匹配一个字符,表示&#39; U&#39;将会失踪

尝试删除

$pattern = "/<a([^>]*) " . "href=\"([^\"]*)\"/";