| Welcome, Guest |
You have to register before you can post on our site.
|
| Online Users |
There are currently 799 online users. » 2 Member(s) | 791 Guest(s) Applebot, Baidu, Bing, DuckDuckGo, Google, Yandex, mar7w7, supersport
|
|
|
| [Tut] How to Upload Files to Google Drive with API using PHP |
|
Posted by: xSicKxBot - 08-04-2022, 06:03 PM - Forum: PHP Development
- No Replies
|
 |
How to Upload Files to Google Drive with API using PHP
 by Vincy. Last modified on August 5th, 2022.
Uploading files to Google Drive programmatically can be done by the Google API. It uses OAuth to authenticate requests and authorize access.
This tutorial describes uploading files to Google Drive using PHP. It gives a simple PHP script to easily understand the Google API and upload files.
It also uses a database to save the uploaded file details with the Google Drive reference.
It handles errors that can occur for the following reasons during the upload process.
- When the file binary is empty on the PHP script.
- When the user fails to submit the form and proceeds to upload without form data.
- When the Google OAuth request is failed to get the access token.
- When the cURL request to the Google API is failed to return the status code 200.
On successful upload without any of the above uncertainties, this code shows the Google Drive link to see the uploaded file preview.
The below figure shows the file upload form with the success and failure responses.

How to create API credentials to access Google Drive
Login to your Google account and go to the developer console. Then follow the below steps to create API credentials to access Google Drive to upload a file.
- Create a new project or select an existing project from the Google console header.
- Click the Library menu and enable Google Drive API. Use the filter to shortlist this API.
- Choose the OAuth consent screen menu to create the app. Fill up the following to register the app.
- App name
- support email
- authorized domain
- developer contact detail (email).
- Select Credentials->Create Credentials, then select OAuth client ID. Then, enter the following details.
- Choose Application type as Web Application.
- Add authorized JavaScript origin.
- Add authorized redirect URI.
After completing these steps, the console will display the Google web client id and the secret key. These credentials are used for the authentication process to get access to Google Drive.

Example application files structure
Let us see the PHP example code created for this article to upload a file to Google Drive. The following figure shows the file structure of this example.

Application config file
This PHP file contains the constants used in this example. The API credentials and the endpoints are stored as PHP constants with this file.
The endpoint URI configured in this file is to hit the Google Drive API for the following purpose.
- To set scope during OAuth redirect.
- To get the access token after authentication with the API credentials
GOOGLE_WEB_CLIENT_ID and GOOGLE_WEB_CLIENT_SECRET.
- To upload file to Drive
- To add metadata to the uploaded file
The AUTHORIZED_REDIRECT_URI is to set the callback. The API will call this URI with the access code to proceed with file upload after authentication.
lib/Config.php
<?php class Config
{ const GOOGLE_WEB_CLIENT_ID = 'add client id'; const GOOGLE_WEB_CLIENT_SECRET = 'add client secret'; const GOOGLE_ACCESS_SCOPE = 'https://www.googleapis.com/auth/drive'; const AUTHORIZED_REDIRECT_URI = 'https://domain-name/php-google-drive-upload/callback.php'; const GOOGLE_OAUTH2_TOKEN_URI = 'https://oauth2.googleapis.com/token'; const GOOGLE_DRIVE_FILE_UPLOAD_URI = 'https://www.googleapis.com/upload/drive/v3/files'; const GOOGLE_DRIVE_FILE_META_URI = 'https://www.googleapis.com/drive/v3/files/';
} ?>
Landing form with file upload option
This is a simple HTML form that calls the PHP endpoint upload.php on submitting. The file data is posted to this PHP file to upload to a local directory and to Google Drive.
I have just managed field validation by using HTML5 required attribute. You can also add exclusive JavaScript validation for this file upload form.
We have already seen code for doing server-side file validation in PHP.
index.php
<?php
session_start(); ?>
<html>
<head>
<title>How to upload file to Google drive</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<link rel="stylesheet" type="text/css" href="css/form.css" />
<style>
input.btn-submit { background: #ffc72c url("google-drive-icon.png") no-repeat center left 45px; text-align: right; padding-right: 45px;
}
</style>
</head>
<body> <div class="phppot-container tile-container"> <form method="post" action="upload.php" class="form" enctype="multipart/form-data">
<?php if(!empty($_SESSION['responseMessage'])){ ?> <div id="phppot-message" class="<?php echo $_SESSION['responseMessage']['messageType']; ?>"> <?php echo $_SESSION['responseMessage']['message']; ?> </div>
<?php $_SESSION['responseMessage'] = "";
}
?>
<h2 class="text-center">Upload file to drive</h2> <div> <div class="row"> <label class="inline-block">Select file to upload</label> <input type="file" name="file" class="full-width" required> </div> <div class="row"> <input type="submit" name="submit" value="Upload to Drive" class="btn-submit full-width"> </div> </div> </form> </div>
</body>
</html>
PHP code upload file to a directory, save to database and redirect to Google
This HTML form action endpoint performs file upload to a directory. It saves the file path to the database and redirects to the Google OAuth URI.
This URI sets the scope, app client id and redirect path (callback.php) to get the access code from the Google Drive API endpoint.
In case of error occurrence, it calls application utils to acknowledge and guide users properly.
upload.php
<?php
session_start();
require_once __DIR__ . '/lib/Util.php';
$util = new Util(); if (! empty($_POST['submit'])) { require_once __DIR__ . '/lib/Config.php'; require_once __DIR__ . '/lib/FileModel.php'; $fileModel = new FileModel(); if (! empty($_FILES["file"]["name"])) { $fileName = basename($_FILES["file"]["name"]); $targetFilePath = "data/" . $fileName; if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)) { $fileInsertId = $fileModel->insertFile($fileName); if ($fileInsertId) { $_SESSION['fileInsertId'] = $fileInsertId; $googleOAuthURI = 'https://accounts.google.com/o/oauth2/auth?scope=' . urlencode(Config::GOOGLE_ACCESS_SCOPE) . '&redirect_uri=' . Config::AUTHORIZED_REDIRECT_URI . '&response_type=code&client_id=' . Config::GOOGLE_WEB_CLIENT_ID . '&access_type=online'; header("Location: $googleOAuthURI"); exit(); } else { $util->redirect("error", 'Failed to insert into the database.'); } } else { $util->redirect("error", 'Failed to upload file.'); } } else { $util->redirect("error", 'Choose file to upload.'); }
} else { $util->redirect("error", 'Failed to find the form data.');
}
?>
Callback action to get access token and proceed file upload to Google Drive
This page is called by Google API after performing the OAuth request. The API sends a code parameter while calling this redirect URL.
It calls the getAccessToken() a function defined in the service class. It passes API credentials to get the access token.
When the token is received, this file builds the file content and file meta to be uploaded to Google Drive via cURL request.
The uploadFileToGoogleDrive() accepts access token and the file information to set the cURL options. It returns the file id of the uploaded file to Google Drive.
Then, the addFileMeta() PHP function accepts the array of file metadata. It returns the Google Drive file meta data received as a cURL response.
This metadata id is used in the success response to allow users to view the uploaded file in Google Drive.
callback.php
<?php
session_start();
require_once __DIR__ . '/lib/Util.php';
$util = new Util();
if (isset($_GET['code'])) { require_once __DIR__ . '/lib/Config.php'; require_once __DIR__ . '/lib/GoogleDriveUploadService.php'; $googleDriveUploadService = new GoogleDriveUploadService(); $googleResponse = $googleDriveUploadService->getAccessToken(Config::GOOGLE_WEB_CLIENT_ID, Config::AUTHORIZED_REDIRECT_URI, Config::GOOGLE_WEB_CLIENT_SECRET, $_GET['code']); $accessToken = $googleResponse['access_token']; if (! empty($accessToken)) { require_once __DIR__ . '/lib/FileModel.php'; $fileModel = new FileModel(); $fileId = $_SESSION['fileInsertId']; if (! empty($fileId)) { $fileResult = $fileModel->getFileRecordById($fileId); if (! empty($fileResult)) { $fileName = $fileResult[0]['file_base_name']; $filePath = 'data/' . $fileName; $fileContent = file_get_contents($filePath); $fileSize = filesize($filePath); $filetype = mime_content_type($filePath); try { // Move file to Google Drive via cURL $googleDriveFileId = $googleDriveUploadService->uploadFileToGoogleDrive($accessToken, $fileContent, $filetype, $fileSize); if ($googleDriveFileId) { $fileMeta = array( 'name' => basename($fileName) ); // Add file metadata via Google Drive API $googleDriveMeta = $googleDriveUploadService->addFileMeta($accessToken, $googleDriveFileId, $fileMeta); if ($googleDriveMeta) { $fileModel->updateFile($googleDriveFileId, $fileId); $_SESSION['fileInsertId'] = ''; $driveLink = '<a href="https://drive.google.com/open?id=' . $googleDriveMeta['id'] . '" target="_blank"><b>Open in Google Drive</b></a>.'; $util->redirect("success", 'File uploaded. ' . $driveLink); } } } catch (Exception $e) { $util->redirect("error", $e->getMessage()); } } else { $util->redirect("error", 'Failed to get the file content.'); } } else { $util->redirect("error", 'File id not found.'); } } else { $util->redirect("error", 'Something went wrong. Access forbidden.'); }
}
?>
PHP service class to prepare requests and hit Google Drive API via cURL
The service class contains functions that build the PHP cURL request to hit the Google Drive API.
All the cURL requests use POST methods to submit parameters to the API endpoints.
It gets the response code and the data in the specified format. In case of a cURL error or getting a response code other than 200, it throws exceptions.
On getting the status code 200, it receives the Google Drive file reference and metadata JSON response appropriately.
lib/GoogleDriveUploadService.php
<?php
require_once __DIR__ . '/Config.php'; class GoogleDriveUploadService
{ public function getAccessToken($clientId, $authorizedRedirectURI, $clientSecret, $code) { $curlPost = 'client_id=' . $clientId . '&redirect_uri=' . $authorizedRedirectURI . '&client_secret=' . $clientSecret . '&code=' . $code . '&grant_type=authorization_code'; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, Config::GOOGLE_OAUTH2_TOKEN_URI); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost); $curlResponse = json_decode(curl_exec($curl), true); $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($responseCode != 200) { $errorMessage = 'Problem in getting access token'; if (curl_errno($curl)) { $errorMessage = curl_error($curl); } throw new Exception('Error: ' . $responseCode . ': ' . $errorMessage); } return $curlResponse; } public function uploadFileToGoogleDrive($accessToken, $fileContent, $filetype, $fileSize) { $curl = curl_init(); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($curl, CURLOPT_URL, Config::GOOGLE_DRIVE_FILE_UPLOAD_URI . '?uploadType=media'); curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $fileContent); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HTTPHEADER, array( 'Content-Type: ' . $filetype, 'Content-Length: ' . $fileSize, 'Authorization: Bearer ' . $accessToken )); $curlResponse = json_decode(curl_exec($curl), true); $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($responseCode != 200) { $errorMessage = 'Failed to upload file to drive'; if (curl_errno($curl)) { $errorMessage = curl_error($curl); } throw new Exception('Error ' . $responseCode . ': ' . $errorMessage); } curl_close($curl); return $curlResponse['id']; } public function addFileMeta($accessToken, $googleDriveFileId, $fileMeta) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, Config::GOOGLE_DRIVE_FILE_META_URI . $googleDriveFileId); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($curl, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Authorization: Bearer ' . $accessToken )); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PATCH'); curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($fileMeta)); $curlResponse = json_decode(curl_exec($curl), true); $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($responseCode != 200) { $errorMessage = 'Failed to add file metadata'; if (curl_errno($curl)) { $errorMessage = curl_error($curl); } throw new Exception('Error ' . $responseCode . ': ' . $errorMessage); } curl_close($curl); return $curlResponse; }
}
?>
PHP model class to build queries and parameters to insert, read and update file data log
This PHP model class defines functions to keep track of the database log for the uploaded file.
In the callback, it writes the Google Drive file id with the reference of the last inserted id in the session.
lib/FileModel.php
<?php
require_once __DIR__ . '/DataSource.php'; class FileModel extends DataSource
{ function insertFile($fileBaseName) { $query = "INSERT INTO google_drive_upload_response_log (file_base_name, create_at) VALUES (?, NOW())"; $paramType = 's'; $paramValue = array( $fileBaseName ); $insertId = $this->insert($query, $paramType, $paramValue); return $insertId; } function getFileRecordById($fileId) { $query = "SELECT * FROM google_drive_upload_response_log WHERE id = ?"; $paramType = 'i'; $paramValue = array( $fileId ); $result = $this->select($query, $paramType, $paramValue); return $result; } function updateFile($googleFileId, $fileId) { $query = "UPDATE google_drive_upload_response_log SET google_file_id=? WHERE id=?"; $paramType = 'si'; $paramValue = array( $googleFileId, $fileId ); $this->update($query, $paramType, $paramValue); }
}
?>
This file is a simple PHP Util class having only a redirect function as of now.
We can enhance this function by adding more utils. For example, it can have JSON encode decode to convert the cURL response into an array.
lib/Util.php
<?php class Util
{ function redirect($type, $message) { $_SESSION['responseMessage'] = array( 'messageType' => $type, 'message' => $message ); header("Location: index.php"); exit(); }
}
?>
Installation steps
Before running this example to upload a file to Google Drive, do the following steps. It will let the development environment be ready with the required configurations and resources.
- Configure database details with lib/DataSource.php. The source code includes this file.
- Configure Google API keys with lib/Config.php. Also, provide the domain and subfolder for setting the callback with AUTHORIZED_REDIRECT_URI.
- Import the below SQL script into your target database.
sql/structure.sql
--
-- Table structure for table `google_drive_upload_response_log`
-- CREATE TABLE `google_drive_upload_response_log` ( `id` int NOT NULL, `google_file_id` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `file_base_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `create_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; --
-- Indexes for dumped tables
-- --
-- Indexes for table `google_drive_upload_response_log`
--
ALTER TABLE `google_drive_upload_response_log` ADD PRIMARY KEY (`id`); --
-- AUTO_INCREMENT for dumped tables
-- --
-- AUTO_INCREMENT for table `google_drive_upload_response_log`
--
ALTER TABLE `google_drive_upload_response_log` MODIFY `id` int NOT NULL AUTO_INCREMENT;
Download
Popular Articles
↑ Back to Top
https://www.sickgaming.net/blog/2022/08/...using-php/
|
|
|
| News - Tencent Is Reportedly Looking To Become Ubisoft's Biggest Shareholder |
|
Posted by: xSicKxBot - 08-04-2022, 06:03 PM - Forum: Lounge
- No Replies
|
 |
Tencent Is Reportedly Looking To Become Ubisoft's Biggest Shareholder
Chinese conglomerate Tencent is reportedly planning to increase its stake in Ubisoft, the French publisher and developer of games such as Assassin's Creed, Far Cry, and many more titles. According to sources that spoke to Reuters, Tencent has reached out to Ubisoft's founding Guillemot family and intends to become the single largest stakeholder in Ubisoft. Tencent currently has a 5% stake in the company that was purchased in 2018, while the Guillemot family has a 15% stake, and is planning to offer up to 100 euros ($101.84) per share to increase its foothold. This figure is "way above" the company's current price and is being offered as a way to keep potential competition away, one of the sources added. Ubisoft was previously valued at $5.3 billion and share prices increased by up to 16% after the Reuters report went live. Reuters sources said that Tencent also plans to acquire shares from public shareholders of Ubisoft, which accounts for 80% of the firm's owned stock. "Tencent is very determined to nail down the deal as Ubisoft is such an important strategic asset for Tencent," one of the sources said. Continue Reading at GameSpot
https://www.gamespot.com/articles/tencen...01-10abi2f
|
|
|
| PC - River City Saga: Three Kingdoms |
|
Posted by: xSicKxBot - 08-04-2022, 06:03 PM - Forum: New Game Releases
- No Replies
|
 |
River City Saga: Three Kingdoms
The River City cast of characters step onto the stage of the Three Kingdoms to wreak havoc! This title takes the concept of the beloved Downtown Special: River City Historical Drama! game and crosses international lines to tell the tale of the Romance of the Three Kingdoms. Watch the wacky and comedic action unfold as our hero Guan Yu (you may recognize him as Kunio) tries to survive the tumultuous times of the late Han dynasty. The rest of the cast make appearances as generals, tacticians, and more, giving the Three Kingdoms a River City twist! Enjoy a funny, action-packed take on famous historical events, from the Yellow Turban Rebellion to the Battle of Red Cliffs. The Beat ‘Em Up Action You Know and Love! The gameplay focuses on the beat ‘em up action the series is known for. Intricately connected areas form a massive game world. Aside from battle, you can enjoy shopping in villages and cities. Go sight-seeing and explore every nook and cranny!
Turn the Tide of Battle with Flashy “Tactics” Moves!
Turn the tides of battle in your favor with flashy “Tactics” moves! You can impact all the enemies on screen with these Tactics. Using them in specific areas could even lead to discoveries such as hidden rooms or passages…? Publisher: Arc System Works Release Date: Jul 21, 2022
https://www.metacritic.com/game/pc/river...e-kingdoms
|
|
|
| [Tut] For Loop with Two Variables (for i j in python) |
|
Posted by: xSicKxBot - 08-03-2022, 05:56 PM - Forum: Python
- No Replies
|
 |
For Loop with Two Variables (for i j in python)
for i j in python
The Python expression for i, j in XXX allows you to iterate over an iterable XXX of pairs of values. For example, to iterate over a list of tuples, this expression captures both tuple values in the loop variables i and j at once in each iteration.
Here’s an example:
for i, j in [('Alice', 18), ('Bob', 22)]: print(i, 'is', j, 'years old')
Output:
Alice is 18 years old
Bob is 22 years old
Notice how the first loop iteration captures i='Alice' and j=18, whereas the second loop iteration captures i='Bob' and j=22.
for i j in enumerate python
The Python expression for i, j in enumerate(iterable) allows you to loop over an iterable using variable i as a counter (0, 1, 2, …) and variable j to capture the iterable elements.
Here’s an example where we assign the counter values i=0,1,2 to the three elements in lst:
lst = ['Alice', 'Bob', 'Carl']
for i, j in enumerate(lst): print(i, j)
Output:
0 Alice
1 Bob
2 Carl
Notice how the loop iteration capture:
i=0 and j='Alice',
i=1 and j='Bob', and
i=2 and j='Carl'.
Learn More: The enumerate() function in Python.
for i j in zip python
The Python expression for i, j in zip(iter_1, iter_2) allows you to align the values of two iterables iter_1 and iter_2 in an ordered manner and iterate over the pairs of elements. We capture the two elements at the same positions in variables i and j.
Here’s an example that zips together the two lists [1,2,3] and [9,8,7,6,5].
for i, j in zip([1,2,3], [9,8,7,6,5]): print(i, j)
Output:
1 9
2 8
3 7
Learn More: The zip() function in Python.
for i j in list python
The Python expression for i, j in list allows you to iterate over a given list of pairs of elements (list of tuples or list of lists). In each iteration, this expression captures both pairs of elements at once in the loop variables i and j.
Here’s an example:
for i, j in [(1,9), (2,8), (3,7)]: print(i, j)
Output:
1 9
2 8
3 7
for i j k python
The Python expression for i, j, k in iterable allows you to iterate over a given list of triplets of elements (list of tuples or list of lists). In each iteration, this expression captures all three elements at once in the loop variables i and j.
Here’s an example:
for i, j, k in [(1,2,3), (4,5,6), (7,8,9)]: print(i, j, k)
Output:
1 2 3
4 5 6
7 8 9
for i j in a b python
Given two lists a and b, you can iterate over both lists at once by using the expression for i,j in zip(a,b).
Given one list ['a', 'b'], you can use the expression for i,j in enumerate(['a', 'b']) to iterate over the pairs of (identifier, list element) tuples.
Summary
The Python for loop is a powerful method to iterate over multiple iterables at once, usually with the help of the zip() or enumerate() functions.
for i, j in zip(range(10), range(10)): # (0,0), (1,1), ..., (9,9)
If a list element is an iterable by itself, you can capture all iterable elements using a comma-separated list when defining the loop variables.
for i,j,k in [(1,2,3), (4,5,6)]: # Do Something
https://www.sickgaming.net/blog/2022/07/...in-python/
|
|
|
| PC - Baldur's Gate: Dark Alliance II |
|
Posted by: xSicKxBot - 08-03-2022, 05:56 PM - Forum: New Game Releases
- No Replies
|
 |
Baldur's Gate: Dark Alliance II
Embark on a new adventure for fortune, glory and power. Baldur's Gate: Dark Alliance II, the sequel to Baldur's Gate: Dark Alliance starts you off on a road full of danger and magic. Face a seemingly endless army of sinister enemies in over 80 levels of finger-numbing action. Master skills, spells and deadly weapons while traveling through spectacular environments. Customize your character and forge your own weapons. It's up to you to rid the lands of evil by yourself or with a friend. Publisher: Interplay Release Date: Jul 20, 2022
https://www.metacritic.com/game/pc/baldu...lliance-ii
|
|
|
| News - Madden 23 Finally Has An Answer For Scrambling, Deep-Ball QBs, Says Producer |
|
Posted by: xSicKxBot - 08-03-2022, 05:56 PM - Forum: Lounge
- No Replies
|
 |
Madden 23 Finally Has An Answer For Scrambling, Deep-Ball QBs, Says Producer
When Madden 23 launches this month, it will come, as always, with several much-touted new features, such as an on-the-field overhaul, collectively called Fieldsense, as well as new wrinkles to the game's Franchise mode, Face of the Franchise mode, and more. With just days to go before launch and a day-zero patch now made public, Madden gameplay producer Clint Oldenburg says the major takeaway from the beta is that the always-vocal Madden fanbase is in lockstep with EA Tiburon when it comes to what this year's game should look, play, and feel like. "The two most active pieces of feedback from the beta were, 'don't significantly change gameplay for launch' and 'please don't nerf the pass coverage,'" Oldenburg told GameSpot. "And we were really excited to get that feedback, because not only did we spend a lot of time working on pass coverage to bring more balance to the deep-passing game, we also brought an increase in pass rush." The fact that players' biggest request so far has essentially been "if it ain't broken, don't fix it," bodes well for launch, Oldenburg believes. Madden 23 is focused greatly on "bringing more balance to the defensive side of the ball," Oldenburg said, and the beta helped greatly in finding the right balance between giving players more influence on defense while still holding true to the league Madden mimics--one that is now pass-happier and higher-scoring than ever before. Continue Reading at GameSpot
https://www.gamespot.com/articles/madden...01-10abi2f
|
|
|
| [Tut] Python RegEx – Match Whitespace But Not Newline |
|
Posted by: xSicKxBot - 08-02-2022, 09:58 PM - Forum: Python
- No Replies
|
 |
Python RegEx – Match Whitespace But Not Newline
Problem Formulation
Challenge: How to design a regular expression pattern that matches whitespace characters such as the empty space ' ' and the tabular character '\t', but not the newline character '\n'?
An example of this would be to replace all whitespaces (except newlines) between a space-delimited file with commas to obtain a CSV.
Method 1: Use Character Class
The character class pattern [ \t] matches one empty space ' ' or a tabular character '\t', but not a newline character. If you want to match an arbitrary number of empty spaces except for newlines, append the plus quantifier to the pattern like so: [ \t]+.
Here’s an example where you replace all separating whitespace (except newline) with a comma to receive a CSV formatted output:
import re txt = 'a \t b c\nd e f'
csv_txt = re.sub('[ \t]+', ',', txt)
print(csv_txt)
Output:
a,b,c
d,e,f
Why the space in the pattern [ \t]?
The reason there’s a space in the pattern is to match the empty space. The character class essentially is an OR relationship, i.e., one item within the character class is matched. For the given pattern, it matches either the empty space ' ' or the tabular character '\t'.
Learn More: Character Class (Character Set) — The Ultimate Guide for Python
Method 2: Match Individual Different Whitespace Characters
The previous method only matches the horizontal tab (U+0009) and breaking space (U+0020) characters. If you want more fine-grained control about which whitespace characters to match and which not, you can use the following baseline approach.
The following list of Unicode whitespace characters UNICODE_WHITESPACES contains all major whitespace variants you may want to check your string for. You can generate a character class using the string expression '[' + ''.join(UNICODE_WHITESPACES) + ']'.
Here’s a variant that finds all matches of whitespace characters in a given text:
import re UNICODE_WHITESPACES = [ "\u0009", # character tabulation "\u000a", # line feed "\u000b", # line tabulation "\u000c", # form feed "\u000d", # carriage return "\u0020", # space "\u0085", # next line "\u00a0", # no-break space "\u1680", # ogham space mark "\u2000", # en quad "\u2001", # em quad "\u2002", # en space "\u2003", # em space "\u2004", # three-per-em space "\u2005", # four-per-em space "\u2006", # six-per-em space "\u2007", # figure space "\u2008", # punctuation space "\u2009", # thin space "\u200A", # hair space "\u2028", # line separator "\u2029", # paragraph separator "\u202f", # narrow no-break space "\u205f", # medium mathematical space "\u3000", # ideographic space
] txt = ' \t\n\r'
pattern = '[' + ''.join(UNICODE_WHITESPACES) + ']'
matches = re.findall(pattern, txt)
print(matches)
# [' ', '\t', '\n', '\r']
Of course, you can restrict this to only contain whitespaces that are not newline-related.
Method 3: Match Individual Different Whitespaces Except Newlines
The following code snippet uses the UNICODE_WHITESPACES constant but comments out the newline whitespaces so that newline-related characters such as '\n' and '\r' are not matched anymore!
import re UNICODE_WHITESPACES = [ "\u0009", # character tabulation # "\u000a", # line feed "\u000b", # line tabulation "\u000c", # form feed # "\u000d", # carriage return "\u0020", # space # "\u0085", # next line "\u00a0", # no-break space "\u1680", # ogham space mark "\u2000", # en quad "\u2001", # em quad "\u2002", # en space "\u2003", # em space "\u2004", # three-per-em space "\u2005", # four-per-em space "\u2006", # six-per-em space "\u2007", # figure space "\u2008", # punctuation space "\u2009", # thin space "\u200A", # hair space # "\u2028", # line separator # "\u2029", # paragraph separator "\u202f", # narrow no-break space "\u205f", # medium mathematical space "\u3000", # ideographic space
] txt = ' \t\n\r'
pattern = '[' + ''.join(UNICODE_WHITESPACES) + ']'
matches = re.findall(pattern, txt)
print(matches)
# [' ', '\t']
Of course, you can comment out the individual whitespace Unicode characters you don’t want to match as required by your own application.
https://www.sickgaming.net/blog/2022/07/...t-newline/
|
|
|
|
|
|