【问题标题】:PHP - Search for an URL patterns in a CSV file and replace itPHP - 在 CSV 文件中搜索 URL 模式并替换它
【发布时间】:2015-05-14 17:56:39
【问题描述】:

我有一个包含多个列的 csv 文件,其中一些列中有一些看起来像 StreamHandler.ashx?SubscriptionID=6348 的 HTML 标记。然后是一个文件夹,其中包含所有使用 ID.Extension 重命名的图像,即 6348.jpg。

我想创建一个搜索StreamHandler.ashx?SubscriptionID=6348 并将其替换为http://newdomain.com/images/6348.jpg 的脚本。

请注意,并非所有文件都是.jpg,因此在找到文件时需要检查扩展名。

$file = fopen("images.csv", "r");

$lines = array();

while (($line = fgetcsv($file)) !== FALSE) {
//$line is an array of the csv elements
$lines[] = $line;
}
foreach ($lines as $line => $data) {
$data = preg_replace_callback('/StreamHandler\.ashx\?SubscriptionID=([0-9]+)/', function($matches) {
   $img = $matches[1]; //get the filename
   $img = glob("/Users/sandro/Sites/test/destination/" . $img . ".*"); //find the file in the fileserver (in the current directory)
   $img[0] = str_replace ( "/Users/sandro/Sites/test/destination/", 'http://newdomain.com/images/', $img[0] );

   if( isset($img[0]) ) { //was there a match?
      return $img[0]; //replace
   }

   return $matches[0]; //dont replace because file doesnt exist
}, $data);

print_r($data);
}

fclose($file);

我已经编写了打开和读取 csv 文件的部分,但仍然缺少搜索。有什么想法吗?

谢谢

【问题讨论】:

  • 你能提供你写的代码吗?最好在发帖之前表明您已经尝试过。
  • 我已经添加了我已经写好的代码
  • 这些字符串前缀是不变的吗?例如,StreamHandler.ashx?SubscriptionID=?
  • preg_matchparse_str \ parse_url 用于查找模式。 fwrite, file_put_contents 用于写入文件
  • StreamHandler.ashx?SubscriptionID= 总是相同的,只是之后的 ID 发生了变化

标签: php regex csv


【解决方案1】:

您可以通过preg_replace_callback 找到您要搜索的字符串,然后查找文件扩展名并替换。

  • 查找要替换的匹配项
  • 通过查找文件名查看文件是否存在
  • 如果存在,替换字符串
  • 如果不存在,保留当前字符串

$csv = preg_replace_callback('/StreamHandler\.ashx\?SubscriptionID=([0-9]+)/', function($matches) {
   $file = $matches[1]; //get the filename
   $file = glob($file .".*"); //find the file in the fileserver (in the current directory)

   if( isset($file[0]) ) { //was there a match?
      return 'http://newdomain.com/images/'. $file[0]; //replace
   }

   return $matches[0]; //dont replace because file doesnt exist
}, $csv);
例子
  • 我有文件6348.png
  • 我的csv 文件保存:StreamHandler.ashx?SubscriptionID=6348,StreamHandler.ashx?SubscriptionID=6349,StreamHandler.ashx?SubscriptionID=635,StreamHandler.ashx?SubscriptionID=64

输出:

http://newdomain.com/images/6348.png,StreamHandler.ashx?SubscriptionID=6349,StreamHandler.ashx?SubscriptionID=635,StreamHandler.ashx?SubscriptionID=64

【讨论】:

  • 输出应该只有newdomain.com/images/6348.png。此脚本是否仅将 /StreamHandler\.ashx\?SubscriptionID=3232 替换为 csv 文件中的新网址?
  • 是的,它只会找到像StreamHandler.ashx?SubscriptionID=6349 这样的字符串,并用新字符串http://newdomain.com/images/6349.png 替换该字符串
  • 好的,如何让它遍历所有 csv 文件行?
  • 所以我设法遍历了整个文档,但现在它需要将新值保存到 csv 文件中,这里有什么帮助吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
  • 2016-05-18
  • 1970-01-01
  • 1970-01-01
  • 2018-07-30
  • 1970-01-01
  • 2014-06-01
相关资源
最近更新 更多