How can the regular expression provided in the thread be optimized for better performance?
The regular expression provided in the thread can be optimized for better performance by using a more efficient pattern. One way to do this is by avoiding unnecessary capturing groups and quantifiers, and by using more specific character classes where possible. Additionally, using non-greedy quantifiers can help prevent excessive backtracking.
$pattern = '/^https?:\/\/(?:www\.)?example\.com\/([a-zA-Z0-9_-]+)\/?$/';
$url = 'https://www.example.com/user123/';
if (preg_match($pattern, $url, $matches)) {
$username = $matches[1];
echo "Username: $username";
} else {
echo "URL does not match the pattern.";
}