求助:使用preg_replace提取Cat-115/Tid-后的数字
Hey there! Let's sort out this regex problem for you. The issue with your current code is that preg_replace('/[^0-9]/', '', $destination) strips all non-numeric characters from the entire string. So for Cat-115/Tid-11, it would output 11511—combining both the Cat and Tid numbers, which isn't what you want.
Instead of replacing characters, we should extract the specific number that comes after Tid- using preg_match, which is designed for finding and capturing patterns in strings. Here's how to do it properly:
Working Code Example
$destination = $_GET['q']; // Example value: Cat-115/Tid-11 // Use preg_match to capture the number after Tid- if (preg_match('/Tid-(\d+)/', $destination, $matches)) { $tidNumber = $matches[1]; echo $tidNumber; // Outputs: 11 } else { // Handle cases where the Tid- pattern isn't found echo "No valid Tid number detected"; }
Breakdown of the Regex
Tid-: Matches the literal string "Tid-" exactly.(\d+): A capture group that grabs one or more digits (\d= any number,+= one or more occurrences).- The
$matchesarray stores the results:$matches[0]= the full matched string (e.g., "Tid-11")$matches[1]= the content of our capture group (just the number "11")
Alternative: Using preg_replace (If You Prefer)
If you really want to use preg_replace, you can target everything except the number after Tid- and replace it with nothing. Here's how:
$tidNumber = preg_replace('/.*Tid-(\d+).*/', '$1', $destination); // For "Cat-115/Tid-11", this returns "11"
Just note that if the Tid- pattern isn't present, this will return the original string—so adding a check (like using preg_match first) is still a good idea.
Quick Note on Security
Since you're using $_GET['q'], make sure to validate or sanitize the input if you plan to use this number in databases, URLs, or other sensitive contexts to avoid security risks like SQL injection or XSS.
内容的提问来源于stack exchange,提问作者Bijan Zand




