【问题标题】:"preg_replace()" not working properly.“preg_replace()”无法正常工作。
【发布时间】:2014-04-17 07:04:08
【问题描述】:

我有一个文本文件,我提取了所有带有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);

【问题讨论】:

  • 你能告诉我们你输入的“file.txt”吗?
  • 你确定你的循环条件是正确的吗?这个循环永远不会执行
  • for($i=0;$i>=50;$i++){ 是非操作。
  • 应该是for ($i=0; $i<=50; $i++) ???
  • 1. 您的循环条件不正确。 2. 您匹配域名的正则表达式不正确。您需要转义正则表达式中的点元字符。试试这个:~http://([a-z]{1,24})\.([a-z^0-9-]{1,23})\.([a-z]{1,3})~3. preg_replace() 不返回匹配项。您需要将其存储在一个变量中,如下所示:$ret = preg_replace(...);echo 它:echo preg_replace(...);

标签: php arrays preg-replace


【解决方案1】:

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

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

【讨论】:

  • 非常感谢先生;)成功了。我总是尝试两个循环 = 因为我忘记了每次吃什么
  • @user3434985:您匹配域名的正则表达式也不正确。请参阅问题下方的my comment
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-01
    • 2012-07-11
    相关资源
    最近更新 更多