PHP - 在CSV文件中搜索URL模式并替换它

I have a csv file with multiple columns, in some of these columns there are some HTML tags that looks like StreamHandler.ashx?SubscriptionID=6348. Then there is a folder that contains all images renamed with ID.Extension i.e. 6348.jpg.

I would like to create a script that searches for StreamHandler.ashx?SubscriptionID=6348 and replaces it with http://newdomain.com/images/6348.jpg.

Note that not all the files are .jpg so the extension needs to be checked when the file is found.

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

I've written the part to open and read the csv file but the search is still missing. Any thoughts?

Thanks

You can do a preg_replace_callback to find the string you want to search, then look the file extension up, and replace.

  • Find matches to replace
  • See if the file exists by looking for the filename
  • If it exists, replace string
  • If it doesn't exist, keep current string

$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);
Example
  • I have the file 6348.png.
  • My csv file holds: StreamHandler.ashx?SubscriptionID=6348,StreamHandler.ashx?SubscriptionID=6349,StreamHandler.ashx?SubscriptionID=635,StreamHandler.ashx?SubscriptionID=64

The output:

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