【发布时间】: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_match或parse_str\parse_url用于查找模式。fwrite,file_put_contents用于写入文件 -
StreamHandler.ashx?SubscriptionID= 总是相同的,只是之后的 ID 发生了变化