Php как найти email

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.

Happy Coding's user avatar

Happy Coding

2,5171 gold badge12 silver badges24 bronze badges

asked Nov 23, 2015 at 6:46

Liz.'s user avatar

3

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

Ricardo Martins's user avatar

answered Nov 23, 2015 at 6:51

Niranjan N Raju's user avatar

Niranjan N RajuNiranjan N Raju

12k4 gold badges22 silver badges41 bronze badges

5

Parsing e-mail addresses is an insane work and would result in a very complicated regular expression. For example, consider this official regular expression to catch an e-mail address: http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html

Amazing right?

Instead, there is a standard php function to do this called mailparse_rfc822_parse_addresses() and documented here.

It takes a string as argument and returns an array of associative array with keys display, address and is_group.

So,

$to = 'Wez Furlong <wez@example.com>, doe@example.com';
var_dump(mailparse_rfc822_parse_addresses($to));

would yield:

array(2) {
  [0]=>
  array(3) {
    ["display"]=>
    string(11) "Wez Furlong"
    ["address"]=>
    string(15) "wez@example.com"
    ["is_group"]=>
    bool(false)
  }
  [1]=>
  array(3) {
    ["display"]=>
    string(15) "doe@example.com"
    ["address"]=>
    string(15) "doe@example.com"
    ["is_group"]=>
    bool(false)
  }
}

answered Jan 3, 2018 at 15:28

Jacques's user avatar

JacquesJacques

9511 gold badge12 silver badges15 bronze badges

3

try this code.

<?php

function extract_emails_from($string){
  preg_match_all("/[._a-zA-Z0-9-]+@[._a-zA-Z0-9-]+/i", $string, $matches);
  return $matches[0];
}

$text = "blah blah blah blah blah blah email2@address.com";

$emails = extract_emails_from($text);

print(implode("n", $emails));

?>

This will work.

Thanks.

answered Nov 23, 2015 at 6:59

Priya Rajaram's user avatar

2

This is based on Niranjan’s response, assuming you have the input email enclosed within < and > characters). Instead of using a regular expression to grab the email address, here I get the text part between the < and > characters. Otherwise, I use the string to get the entire email. Of course, I didn’t make any validation on the email address, this will depend on your scenario.

<?php 
    $string = 'Ruchika <ruchika@example.com>';
    $pattern = '/<(.*?)>/i';

    preg_match_all($pattern, $string, $matches);
    var_dump($matches);
    $email = $matches[1][0] ?? $string;
    echo $email;
?>

Here is a forked demo.

Of course, if my assumption isn’t correct, then this approach will fail. But based on your input, I believe you wanted to extract emails enclosed within < and > chars.

answered Dec 15, 2017 at 19:01

julianm's user avatar

julianmjulianm

8698 silver badges13 bronze badges

2

This function extract all email from a string and return it in an array.

function extract_emails_from($string){
    preg_match_all( '/([w+.]*w+@[w+.]*w+[w+-w+]*.w+)/is', $string, $matches );
    return $matches[0];
};

answered Jan 14, 2022 at 15:36

Giuseppe Canale's user avatar

This works great and it’s minimal:

$email = strpos($from, '<') ? substr($from, strpos($from, '<') + 1, -1) : $from

answered Jan 13, 2021 at 16:43

Federico Schiocchet's user avatar

2

use (my) function getEmailArrayFromString to easily extract email adresses from a given string.

<?php

function getEmailArrayFromString($sString = '')
{
    $sPattern = '/[._p{L}p{M}p{N}-]+@[._p{L}p{M}p{N}-]+/u';
    preg_match_all($sPattern, $sString, $aMatch);
    $aMatch = array_keys(array_flip(current($aMatch)));

    return $aMatch;
}

// Example
$sString = 'foo@example.com XXX bar@example.com XXX <baz@example.com>';

$aEmail = getEmailArrayFromString($sString);

/**
* array(3) {
    [0]=>
        string(15) "foo@example.com"
    [1]=>
        string(15) "bar@example.com"
    [2]=>
        string(15) "baz@example.com"
    }
*/
var_dump($aEmail);

answered Oct 20, 2018 at 9:22

Guido K.B.W. Üffing's user avatar

0

Based on Priya Rajaram’s code, I have optimised the function a little more so that each email address only appears once.

If, for example, an HTML document is parsed, you usually get everything twice, because the mail address is also used in the mailto link, too.

function extract_emails_from($string){
  preg_match_all("/[._a-zA-Z0-9-]+@[._a-zA-Z0-9-]+/i", $string, $matches);
  return array_values(array_unique($matches[0]));
}

answered Dec 15, 2020 at 17:17

Marco's user avatar

MarcoMarco

3,4204 gold badges23 silver badges34 bronze badges

1

This will work even on subdomains. It extracts all emails from text.

$marches[0] has all emails.

$pattern = "/[a-zA-Z0-9-_]{1,}@[a-zA-Z0-9-_]{1,}(.[a-zA-Z]{1,}){1,}/";
preg_match_all ($pattern , $string, $matches);
print_r($matches);

$marches[0] has all emails.

Array
(
    [0] => Array
        (
            [0] => clotdesormakilgehr@prednisonecy.com
            [1] => **********@******.co.za.com
            [2] => clotdesormakilgehr@prednisonecy.com
            [3] => clotdesormakilgehr@prednisonecy.mikedomain.com
            [4] => clotdesormakilgehr@prednisonecy.com
        )

    [1] => Array
        (
            [0] => .com
            [1] => .com
            [2] => .com
            [3] => .com
            [4] => .com
        )

)

answered May 9, 2020 at 7:06

katwekibs's user avatar

katwekibskatwekibs

1,29214 silver badges17 bronze badges

1

A relatively straight forward approach is to use PHP built-in methods for splitting texts into words and validating E-Mails:

function fetchEmails($text) {
    $words = str_word_count($text, 1, '.@-_1234567890');
    return array_filter($words, function($word) {return filter_var($word, FILTER_VALIDATE_EMAIL);});
}

Will return the e-mail addresses within the text variable.

answered Aug 18, 2020 at 11:03

klawipo's user avatar

2

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_searchThis function returns an array of messages matching the given search criteria

Description

imap_search(
    IMAPConnection $imap,
    string $criteria,
    int $flags = SE_FREE,
    string $charset = «»
): array|false

For example, to match all unanswered messages sent by Mom, you’d
use: «UNANSWERED FROM mom». Searches appear to be case
insensitive. This list of criteria is from a reading of the UW
c-client source code and may be incomplete or
inaccurate (see also » RFC1176,
section «tag SEARCH search_criteria»).

Parameters

imap

An IMAPConnection instance.

criteria

A string, delimited by spaces, in which the following keywords are
allowed. Any multi-word arguments (e.g.
FROM "joey smith") must be quoted. Results will match
all criteria entries.


  • ALL — return all messages matching the rest of the criteria

  • ANSWERED — match messages with the \ANSWERED flag set

  • BCC «string» — match messages with «string» in the Bcc: field

  • BEFORE «date» — match messages with Date: before «date»

  • BODY «string» — match messages with «string» in the body of the message

  • CC «string» — match messages with «string» in the Cc: field

  • DELETED — match deleted messages

  • FLAGGED — match messages with the \FLAGGED (sometimes
    referred to as Important or Urgent) flag set

  • FROM «string» — match messages with «string» in the From: field

  • KEYWORD «string» — match messages with «string» as a keyword

  • NEW — match new messages

  • OLD — match old messages

  • ON «date» — match messages with Date: matching «date»

  • RECENT — match messages with the \RECENT flag set

  • SEEN — match messages that have been read (the \SEEN flag is set)

  • SINCE «date» — match messages with Date: after «date»

  • SUBJECT «string» — match messages with «string» in the Subject:

  • TEXT «string» — match messages with text «string»

  • TO «string» — match messages with «string» in the To:

  • UNANSWERED — match messages that have not been answered

  • UNDELETED — match messages that are not deleted

  • UNFLAGGED — match messages that are not flagged

  • UNKEYWORD «string» — match messages that do not have the
    keyword «string»

  • UNSEEN — match messages which have not been read yet
flags

Valid values for flags are
SE_UID, which causes the returned array to
contain UIDs instead of messages sequence numbers.

charset

MIME character set to use when searching strings.

Return Values

Returns an array of message numbers or UIDs.

Return false if it does not understand the search
criteria or no messages have been found.

Changelog

Version Description
8.1.0 The imap parameter expects an IMAPConnection
instance now; previously, a valid imap resource was expected.

Examples

Example #1 imap_search() example


<?php
$imap
= imap_open('{imap.example.com:993/imap/ssl}INBOX', 'foo@example.com', 'pass123', OP_READONLY);$some = imap_search($imap, 'SUBJECT "HOWTO be Awesome" SINCE "8 August 2008"', SE_UID);
$msgnos = imap_search($imap, 'ALL');
$uids = imap_search($imap, 'ALL', SE_UID);print_r($some);
print_r($msgnos);
print_r($uids);
?>

The above example will output
something similar to:

Array
(
    [0] => 4
    [1] => 6
    [2] => 11
)
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
)
Array
(
    [0] => 1
    [1] => 4
    [2] => 6
    [3] => 8
    [4] => 11
    [5] => 12
)

See Also

  • imap_listscan() — Returns the list of mailboxes that matches the given text

Anonymous

10 years ago


The date format for e.g. SINCE is, according to rfc3501:

date            = date-text / DQUOTE date-text DQUOTE

date-day        = 1*2DIGIT
                    ; Day of month

date-day-fixed  = (SP DIGIT) / 2DIGIT
                    ; Fixed-format version of date-day

date-month      = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" /
                  "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec"

date-text       = date-day "-" date-month "-" date-year

So a valid date is e.g. "22-Jul-2012" with or without the double quotes.


mail at nikha dot org

9 years ago


Hi,
be aware, that imap_search() does NOT (as you may exspect) return an empty array, if nothing was found!
As the manual says, it returns FALSE.

Do not test the result like "count($array)" as I did.
This gives you 1 for an empty result. Took me an hour to found out why :-(  RTFM


britty dot it at hotmail dot com

7 years ago


imap_search function is not fully compatible with IMAP4. the c-client used as of now supports only IMAP2 and some search criterion will not be available for use such as "OR"

So a php code similar to:
$inbox   = imap_open('{imap.example.com:993/imap/ssl}INBOX', 'foo@example.com', 'pass123', OP_READONLY);
$search_string = 'SUBJECT "FedEx" OR SUBJECT "USPS"';   
$emails = imap_search($inbox, $search_string);

will throw an error saying "Unknown search criterion"

observations and reference:

PHP source trace:(ref: https://github.com/php/php-src/blob/master/ext/imap/php_imap.c)
    /ext/imap/php_imap.c -> line no : 4126
    imap_search => line no : 4148

c-client library source trace:
src/c-client/mail.c -> line no : 3973

internal.txt -> line no : 1919 => mail_criteria()
    criteria IMAP2-format search criteria string
    WARNING: This function does not accept IMAP4 search criteria.

IMAP2 RFC1064 => [ref: https://tools.ietf.org/html/rfc1064] [page: 13]
IMAP4 RFC2060 => [ref: http://www.faqs.org/rfcs/rfc2060.html] [section: 6.4.4]

Note:
The core search functionality in a core module(IMAP) is still not available in PHP. Hope this will be brought to the developer community's attention...


james at medbirdie dot com

10 years ago


To set your own CHARSET, which is useful if you are dealing with Chinese Japanese and Korean queries.

<?php imap_search($inbox,'BODY "'.$keyword.'"', SE_FREE, "UTF-8"); ?>


joseph dot cardwell at jbcwebservices dot com

11 years ago


imap_search() always returns false when op_silent flag is set in the connection parameters.

Steve

1 year ago


It has been noted that imap_search breaks with imap4 syntax.  To do an imap 4 search use curl and send a custom command, then grab the results.  Its best to do a UID search to get the unique IDs to work with later.  Here's an example with a working curl function.

<?php
$host
= 'your-server.tld';
$user = 'username';
$pass = 'password';
$folder = 'INBOX';

function

send_imap_command($server, $user, $pass, $command, $folder="INBOX")
{  
//Send an imap command directly to the imap server$result=["response"=>"", "error"=>""];
   
$url = "imaps://$server/". rawurlencode($folder);
   
$options=[CURLOPT_URL=>$url, CURLOPT_PORT=> 993, CURLOPT_USERNAME=> $user,
       
CURLOPT_PASSWORD=> $pass, CURLOPT_RETURNTRANSFER=> true, CURLOPT_HEADER=> true,
       
CURLOPT_CUSTOMREQUEST=> $command];
   
$ch = curl_init();
   
curl_setopt_array($ch, $options);$result["response"] = curl_exec($ch);
    if(
curl_errno($ch)) $response["error"]="Error (". curl_errno($ch) ."): ". curl_error($ch);

    return

$result;
}
//Pull out all the emails returned as undeliverable by the remote mail server in the inbox using curl
$response=send_imap_command($host, $user, $pass,
           
'UID SEARCH SINCE "01-Jan-2022" (OR FROM "mailer-daemon" FROM "postmaster") (OR SUBJECT "fail" (OR SUBJECT "undeliver" SUBJECT "returned"))',
           
$folder);

if(

$response["error"]!="")
{
    echo
$response["error"]."n";
} elseif (
strlen($response["response"])>5){
   
//Server returns a string in the form * SEARCH uid1 uid2 uid3 ...  Clean up and create array of UIDs.
   
$response["response"]=str_replace("* SEARCH ","",$response["response"]);
   
$messages=explode(" ",$response["response"]);
}
print_r($messages);
?>


Enriqe

2 years ago


Please be aware about UID of the message.
It is NOT an ID that never change!

If you move your message to another folder in your IMAP account, this UID WILL CHANGE.

So if your message has UID = 100 (in INBOX folder) and you move it to some subfolder and then back to INBOX, it's new UID in INBOX will be 101.


Paula

6 years ago


This is the correct way to use the imap_search with ON "date"

$date = date("j F Y");

$emails = imap_search($inbox,'ON "'.$date.'"' );


trimoreau dot yonn at gmail dot com

9 years ago


It's not possible to find strings containing double quotes using this function.

For example, if you got a message named : Hello, this is "Bob"
You can try :
     imap_search($inbox, 'SUBJECT "Hello, this is "Bob""')
Or
     imap_search($inbox, "SUBJECT 'Hello, this is "Bob"'")

But both are false, because you did not escape double quotes in the first case, and you can NOT use simple quotes in the imap_search criteria in the second case.

The real problem is that you cannot use simple quotes to surround your criteria in the 2nd argument of imap_search, after SUBJECT.


oliver at samera dot com dot py

20 years ago


imap_search() only supports IMAP2 search criterias, because the function mail_criteria() (from c-client lib) is used in ext/imap/php_imap.c for parsing the search string.
IMAP2 search criteria is defined in RFC 1176, section "tag SEARCH search_criteria".

admin at rancid-tea dot com

15 years ago


This search looks for messages matching ALL criteria, not ANY criteria. For example the search

imap_search($mailbox,'FROM "user" TO "user"')

Will return message that have "user" in both the from and to headers, but not messages with "user" in either the from or to header.


Brett

11 years ago


I haven't found any documentation of the allowed date formats, but (for example) "14 May 2012" works.

// Find UIDs of messages within the past week
$date = date ( "d M Y", strToTime ( "-7 days" ) );
$uids = imap_search ( $mbox, "SINCE "$date"", SE_UID );


andrea dot job at libero dot it

8 years ago


the second parameter about Criteria does not work well on ON criterion.
In facts if I wish to put parameters from $_get into the format Day-Month-Year (01-01-14 for example) will return Unknown criterion etc.
Probably is not the right format ?

Even with for example Thu-Jan-2014 get the same message.


samy.sadi.contact in gmail

3 years ago


utf-8 charset isn't supported on outlook 365. So you might get a false return value here, if you pass that charset.

oliver at samera dot com dot py

21 years ago


imap_search() return false if it does not understand the search condition or no messages have been found.

$emails imap_seach($mbox, "UNDELETED SENTSINCE 01-Jan-2002");
if($emails === false)
  echo "The search failed";


Anonymous

8 years ago


about my previous note:

<<the second parameter about Criteria does not work well on ON criterion.
In facts if I wish to put parameters from $_get into the format Day-Month-Year (01-01-14 for example) will return Unknown criterion etc.
Probably is not the right format ?

Even with for example Thu-Jan-2014 get the same message. >>
------------------------------------------------------------------------

Now works ;)

Just to pass not a date string into criteria parameter but a timestamp returned by mktime function, where you can put your date string.

Solution for any date/time criterion is a unix timestamp.


tgely

6 years ago


If email subject is encoded than use encoding charset and option in search  to find something.

Mail Header:

Subject: =?UTF-8?Q?XYZ?=

<?php imap_search($inbox,'SUBJECT "'.$keyword.'"', SE_FREE, "UTF-8"); ?>


anonymous at anonymous dot ru

9 years ago


the function "imap_search" not work for some mails , maybe that because header syntax or some bug .

thanks a lot


Рекурсивный акроним словосочетания «PHP: Hypertext Preprocessor»
Добро пожаловать на форум PHP программистов!

Главная
Документация
Новости
Форум

За последние 24 часа нас посетил 11001 программист и 930 роботов. Сейчас ищут 600 программистов …

Как извлечь е-майл адреса из текста?

Тема в разделе «Регулярные выражения», создана пользователем Ramzay, 7 фев 2015.


  1. Ramzay

    Ramzay
    Новичок

    С нами с:
    16 янв 2015
    Сообщения:
    11
    Симпатии:
    0

    Нужно выделить из текста эл.адреса и поместить их в массив, в текст(построчно) или еще куда-нибудь, откуда их потом можно будет извлечь.

    Пробую делать так:

    Код (Text):
    1. $instr=’
    2. выадфывадфы
    3. asdf a@b.com asdf
    4. ssssss s@y.com wwwww
    5. sdafllasdkf’;
    6. $matches = preg_match_all(‘/.+@.+/’, $instr,$out);
    7. echo «matches=$matches <br>»;
    8.  print_r($out);

    Программа возвращает массив, который содержит строки, которые содержат адреса.
    Может я неправильно написал выражение, может не ту функцию применил?
    Как получить адреса в чистом виде?

    #1


    Ramzay,

    7 фев 2015


  2. denis01

    denis01
    Суперстар

    Команда форума
    Модератор

    С нами с:
    9 дек 2014
    Сообщения:
    12.236
    Симпатии:
    1.716
    Адрес:
    Молдова, г.Кишинёв

    А зачем их извлекать из текста? Может попросить вписывать в форму, так легче их получить.

    #2


    denis01,

    7 фев 2015


  3. Ramzay

    Ramzay
    Новичок

    С нами с:
    16 янв 2015
    Сообщения:
    11
    Симпатии:
    0

    Таково условие задачи

    #3


    Ramzay,

    7 фев 2015


  4. igordata

    igordata
    Суперстар

    Команда форума
    Модератор

    С нами с:
    18 мар 2010
    Сообщения:
    32.415
    Симпатии:
    1.768

    спам бота сборщика мыла пишешь? тут такое не приветствуется.

    #4


    igordata,

    7 фев 2015


  5. rognorog

    rognorog
    Новичок

    С нами с:
    7 июл 2014
    Сообщения:
    330
    Симпатии:
    0

    Код (PHP):
    1. $instr=
    2. выадфывадфы
    3. asdf ass@b.com asdf
    4. ssssss s@y.com wwwww newmail@сайт.рф
    5. sdafllasdkf’;
    6. $array=array();
    7. preg_match_all(‘/[a-z0-9]+@w+.[a-zрф]{2,}/iu’,$instr,$array);
    8. print_r($array); 
    Код (PHP):
    1. Array
    2. (
    3.     [0] => Array
    4.         (
    5.             [0] => ass@b.com
    6.             [1] => s@y.com
    7.             [2] => newmail@сайт.рф
    8.         )
    9. ) 

    #5


    rognorog,

    9 фев 2015

(Вы должны войти или зарегистрироваться, чтобы разместить сообщение.)

Показать игнорируемое содержимое

Ваше имя или e-mail:
У Вас уже есть учётная запись?
  • Нет, зарегистрироваться сейчас.
  • Да, мой пароль:
  • Забыли пароль?

Запомнить меня

Получение данных с помощью функций preg_match() и preg_match_all().

1

Текст из скобок

Извлечение содержимого из круглых, квадратных и фигурных скобок:

$text = '
	Телеобъектив: диафрагма [ƒ/2.8]
	Широкоугольный объектив: (диафрагма ƒ/1.8)
	По беспроводной сети: {до 13 часов}
	Поддержка диапазона: <Dolby Vision и HDR10>
';

/* [...] */
preg_match_all("/[(.+?)]/", $text, $matches);
print_r($matches[1]);

/* (...) */
preg_match_all("/((.+?))/", $text, $matches);
print_r($matches[1]);

/* {...} */
preg_match_all("/{(.+?)}/", $text, $matches);
print_r($matches[1]);

/* <...> */
preg_match_all("/<(.+?)>/", $text, $matches);
print_r($matches[1]);

PHP

Результат:

Array 
(
    [0] => ƒ/2.8
)
Array 
(
    [0] => диафрагма ƒ/1.8
)
Array
(
    [0] => до 13 часов
)
Array
(
    [0] => Dolby Vision и HDR10
)

2

Текст из HTML тегов

$text = '
	<title>Тег TITLE</title>
	<h1>Тег H1</h1>
	<p>Текст 1</p>
	<p>Текст 2</p>
';

/* <title> */
preg_match('/<title[^>]*?>(.*?)</title>/si', $text, $matches);
echo $matches[1];

/* <h1> */
preg_match('/<h1[^>]*?>(.*?)</h1>/si', $text, $matches);
echo $matches[1];

/* Извлекает текст из всех <p> */
preg_match_all('/<p[^>]*?>(.*?)</p>/si', $text, $matches);
print_r($matches[1]);

PHP

Результат:

Тег TITLE

Тег H1

Array
(
    [0] => Текст 1
    [1] => Текст 2
)

3

URL из текста

$text = 'Text http://ya.ru text http://google.ru text.';
preg_match_all('/(http://|https://)?(www)?([da-z.-]+).([a-z.]{2,6})([/w.-?%&]*)*/?/i', $text, $matches);
print_r($matches[0]);

PHP

Результат:

Array
(
    [0] => http://ya.ru
    [1] => http://google.ru
)

4

href из ссылок

$text = '
	<a href="http://ya.ru">Яндекс</a>
	<a href="http://google.ru">Google</a>
	<a href="http://mail.ru">Mail.ru</a>
';

preg_match_all('/<a.*?href=["'](.*?)["'].*?>/i', $text, $matches);
print_r($matches[1]);

PHP

Результат:

Array
(
    [0] => http://ya.ru
    [1] => http://google.ru
    [2] => http://mail.ru
)

5

Анкоры ссылок

$text = '
	<a href="http://ya.ru">Яндекс</a>
	<a href="http://google.ru">Google</a>
	<a href="http://mail.ru">Mail.ru</a>
';

preg_match_all('/<a.*?>(.*?)</a>/i', $text, $matches);
print_r($matches[1]);

PHP

Результат:

Array
(
    [0] => Яндекс
    [1] => Google
    [2] => Mail.ru
)

6

Src из тегов img

$text = 'text <img alt="" src="/logo.png"> text';
preg_match_all('/<img.*src="(.*)".*>/is', $text, $matches);
print_r($matches[1]);

PHP

Результат:

Array
(
    [0] => /logo.png
)

7

E-mail адреса из текста

$text = 'text admin@mail.ru text text text admin@ya.ru';
preg_match_all('/([a-z0-9_-]+.)*[a-z0-9_-]+@([a-z0-9][a-z0-9-]*[a-z0-9].)+[a-z]{2,6}/i', $text, $matches);
print_r($matches[0]);

PHP

Результат:

Array
(
    [0] => admin@mail.ru
    [1] => admin@ya.ru
)

8

Цвета

HEX/HEXA

$css = '
	body {
		color: #000;
		background: #4545;
	}
	header {
		color: #111111;
		background: #00000080;
	}
';

preg_match_all('/#(?:[0-9a-f]{3,8})/i', $css, $matches);	
print_r($matches[0]);

PHP

Результат:

Array
(
    [0] => #000
    [1] => #4545
    [2] => #111111
    [3] => #00000080
)

RGB/RGBA

$css = '
	body {
		color: rgb(0,0,0); 
		background: rgba(17,85,68,0.33);
	}
	header {
		color: rgb(17,17,17); 
		background: rgba(0,0,0,0.5);
	}
';
 
preg_match_all('/((rgba)((d{1,3},s?){3}(1|0?.?d+))|(rgb)(d{1,3}(,s?d{1,3}){2}))/i', $css, $matches);	
print_r($matches[0]);

PHP

Array
(
    [0] => rgb(0,0,0)
    [1] => rgba(17,85,68,0.33)
    [2] => rgb(17,17,17)
    [3] => rgba(0,0,0,0.5)
)

Я хочу извлечь адрес электронной почты из строки, например:

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

Из приведенной выше строки я хочу получить только адрес электронной почты ruchika@example.com,

Просьба порекомендовать, как этого добиться.

8

Решение

Попробуй это

<?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]);
?>

увидеть демо здесь

Второй метод

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

Увидеть демо здесь

18

Другие решения

Парсинг адресов электронной почты — безумная работа, которая может привести к очень сложному регулярному выражению. Например, рассмотрим это официальное регулярное выражение, чтобы поймать адрес электронной почты: http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html

Удивительно верно?

Вместо этого есть стандартная функция php, которая называется mailparse_rfc822_parse_addresses() и задокументировано Вот.

Он принимает строку в качестве аргумента и возвращает массив ассоциативного массива с ключами display, address и is_group.

Так,

$to = 'Wez Furlong <wez@example.com>, doe@example.com';
var_dump(mailparse_rfc822_parse_addresses($to));

даст:

array(2) {
[0]=>
array(3) {
["display"]=>
string(11) "Wez Furlong"["address"]=>
string(15) "wez@example.com"["is_group"]=>
bool(false)
}
[1]=>
array(3) {
["display"]=>
string(15) "doe@example.com"["address"]=>
string(15) "doe@example.com"["is_group"]=>
bool(false)
}
}

12

Это основано на ответе Ниранджана, при условии, что у вас есть входящий адрес электронной почты, заключенный в < и> персонажи). Вместо использования регулярного выражения для получения адреса электронной почты, здесь я получаю текстовую часть между < и> персонажи. В противном случае я использую строку, чтобы получить всю электронную почту. Конечно, я не проверял адрес электронной почты, это будет зависеть от вашего сценария.

<?php
$string = 'Ruchika <ruchika@example.com>';
$pattern = '/<(.*?)>/i';

preg_match_all($pattern, $string, $matches);
var_dump($matches);
$email = $matches[1][0] ?? $string;
echo $email;
?>

Вот раздвоенный демо.

Конечно, если мое предположение неверно, то такой подход не удастся. Но, исходя из вашего вклада, я считаю, что вы хотели извлечь письма, вложенные в < и> символы.

2

попробуйте этот код.

<?php

function extract_emails_from($string){
preg_match_all("/[._a-zA-Z0-9-]+@[._a-zA-Z0-9-]+/i", $string, $matches);
return $matches[0];
}

$text = "blah blah blah blah blah blah email2@address.com";

$emails = extract_emails_from($text);

print(implode("n", $emails));

?>

Это будет работать

Благодарю.

1

Вы также можете попробовать:

email=re.findall(r'S+@S+','ruchika@example.com')
print email

где S означает любой не пробельный символ

-1

Нашел несколько полезных коды как ниже,

<?php
// input: My Test Email <some.test.email@somewhere.net>

function get_displayname_from_rfc_email($rfc_email_string) {
// match all words and whitespace, will be terminated by '<'
$name = preg_match('/[ws]+/', $rfc_email_string, $matches);
$matches[0] = trim($matches[0]);
return $matches[0];
}
// Output: My Test Email

function get_email_from_rfc_email($rfc_email_string) {
// extract parts between the two parentheses
$mailAddress = preg_match('/(?:<)(.+)(?:>)$/', $rfc_email_string, $matches);
return $matches[1];
}
// Output: some.test.email@somewhere.net
?>

Надеюсь, это кому-нибудь поможет.

-1

использовать (мою) функцию getEmailArrayFromString легко извлечь адреса электронной почты из заданной строки.

<?php

function getEmailArrayFromString($sString = '')
{
$sPattern = '/[._p{L}p{M}p{N}-]+@[._p{L}p{M}p{N}-]+/u';
preg_match_all($sPattern, $sString, $aMatch);
$aMatch = array_keys(array_flip(current($aMatch)));

return $aMatch;
}

// Example
$sString = 'foo@example.com XXX bar@example.com XXX <baz@example.com>';

$aEmail = getEmailArrayFromString($sString);

/**
* array(3) {
[0]=>
string(15) "foo@example.com"[1]=>
string(15) "bar@example.com"[2]=>
string(15) "baz@example.com"}
*/
var_dump($aEmail);

-1

Понравилась статья? Поделить с друзьями:
  • Как составить кроссворд на ноутбуке
  • Как составить бизнес план в екатеринбурге
  • Как составить описание к сказке
  • Как найти сток в европе
  • Площадь шестиугольника формула неправильного как найти