How can substr be used in conjunction with preg_match to extract unknown strings in PHP?

When using preg_match to extract unknown strings in PHP, you can combine it with substr to extract specific parts of the matched string. After using preg_match to find the desired pattern, you can then use substr to extract a portion of the matched string based on its position or length.

// Example code snippet
$string = "Hello, my email is example@example.com";
$pattern = '/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/';
if (preg_match($pattern, $string, $matches)) {
    $email = $matches[0];
    $username = substr($email, 0, strpos($email, '@'));
    echo "Email: $email\n";
    echo "Username: $username\n";
}