Skip to content
Advertisement

Extract email address from string – php

I want to extract email address from a string, for example:

<?php // code
$string = 'Ruchika <ruchika@example.com>';
?>

From the above string I only want to get email address ruchika@example.com.

Kindly, recommend how to achieve this.

Advertisement

Answer

Try this

<?php 
    $string = 'Ruchika < ruchika@example.com >';
    $pattern = '/[a-z0-9_-+.]+@[a-z0-9-]+.([a-z]{2,4})(?:.[a-z]{2})?/i';
    preg_match_all($pattern, $string, $matches);
    var_dump($matches[0]);
?>

see demo here

Second method

<?php 
    $text = 'Ruchika < ruchika@example.com >';
    preg_match_all("/[._a-zA-Z0-9-]+@[._a-zA-Z0-9-]+/i", $text, $matches);
    print_r($matches[0]);
?>

See demo here

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement