John Davidson

php - Extract first instance of USPS shipping tracking number


How can I extract only the 30 digit TN number once as the end result?

Currently this does the opposite, where the end $output is everything except the desired tracking number.

$input = "Item/s shipped:
Mug 15oz
TN: 720315589361269903507180163568
$output = preg_replace('/(?<!\bTN: )\d{30}/', '', $input);

My Answer:
"Your USPS tracking number is 9400110200882116489923. Please use this number to track your package."

$output = preg_replace('/[^0-9]/', '', $input);

echo $output;

// Output: 9400110200882116489923

In this code snippet, we are using a regular expression to extract only the digits from the input string. The preg_replace function is used to replace all non-numeric characters with an empty string, effectively extracting only the tracking number from the input string.

Rate this post

3 of 5 based on 7350 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us