What are some common pitfalls to avoid when using regex in PHP to manipulate strings?

One common pitfall to avoid when using regex in PHP to manipulate strings is not properly escaping special characters. This can lead to unexpected behavior or errors in the regex pattern. To solve this issue, make sure to use the preg_quote() function to escape special characters before using them in the regex pattern.

// Incorrect way to use regex without escaping special characters
$string = "Hello, world!";
$pattern = "/Hello, world!/";
$result = preg_match($pattern, $string);

// Correct way to use regex with escaped special characters
$string = "Hello, world!";
$escaped_string = preg_quote("Hello, world!", '/');
$pattern = "/$escaped_string/";
$result = preg_match($pattern, $string);