“preg_replace()”无法正常工作。

时间:2014-04-17 07:04:08

标签: php arrays preg-replace

我有一个文本文件,我提取了所有使用http://加入的域名地址 现在我要替换所有http://。在我的匹配数组中带有“”但没有发生任何事情甚至没有出现错误

$list = file_get_contents( 'file.txt' );
preg_match_all( "/http:\/\/.([a-z]{1,24}).([a-z^0-9-]{1,23}).([a-z]{1,3})/", $list, $matches );

for ($i=0; $i>=50; $i++) {
    $pattern = array();
    $replacement = array();
    $pattern[0][$i] = "/http:\/\/.[w-w]{1,3}/";
    $replacement[0][$i] = '';

    preg_replace( $pattern[0][$i], $replacement[0][$i], $matches[0][$i] );
}

print_r($matches);

2 个答案:

答案 0 :(得分:1)

您的循环永远不会运行,因为0 >= 50会产生false。也就是说,您正在寻找的是地图操作:

$matches = array_map(function($match) {
    return preg_replace('~^http://w{1,3}~', '', $match);
}, $matches[0]);
print_r($matches);

答案 1 :(得分:0)

preg_match_all也有问题。正则表达式中的句点与任何字符匹配。

$list = file_get_contents( 'file.txt' );
preg_match_all( "/http:\/\/([a-z]{1,24})\.([a-z^0-9-]{1,23})\.([a-z]{1,3})/", $list, $matches );

$pattern = "/http:\/\/(.[w-w]{1,3})/";
$replacement = '$1';
$matches[0] = preg_replace( $pattern, $replacement, $matches[0] );

print_r($matches);