What are the potential pitfalls of using preg_replace for string manipulation in PHP?

Potential pitfalls of using preg_replace for string manipulation in PHP include the risk of introducing security vulnerabilities such as allowing for code injection through malicious patterns. To mitigate this risk, it is important to sanitize input data and use proper regular expressions to ensure safe replacements.

// Example of using preg_replace with proper sanitization and validation
$input = $_POST['input']; // Assuming input comes from a form submission

// Sanitize input
$sanitized_input = filter_var($input, FILTER_SANITIZE_STRING);

// Validate input
if (preg_match('/^[a-zA-Z0-9\s]+$/', $sanitized_input)) {
    // Perform safe string manipulation
    $output = preg_replace('/pattern/', 'replacement', $sanitized_input);
} else {
    echo "Invalid input";
}