What are the best practices for validating and extracting numerical values from text input in PHP, especially when dealing with dynamic content like image IDs?

When validating and extracting numerical values from text input in PHP, especially when dealing with dynamic content like image IDs, it is important to use regular expressions to ensure that only valid numerical values are accepted. This can help prevent SQL injection attacks and other security vulnerabilities. Additionally, it is recommended to sanitize the input to remove any unwanted characters or tags before processing the data.

// Example of validating and extracting numerical values from text input in PHP
$input = "Image ID: 1234";
$pattern = '/\d+/'; // Regular expression to match numerical values
if (preg_match($pattern, $input, $matches)) {
    $imageID = $matches[0];
    // Process the extracted image ID
    echo "Image ID: " . $imageID;
} else {
    echo "Invalid input";
}