How to extract Email & Name from Full Email text using PHP? - php

I have a string as
$email_string='Aslam Doctor <aslam.doctor#gmail.com>';
From which I want to extract Name & Email using PHP? so that I can get
$email='aslam.doctor#gmail.com';
$name='Aslam Doctor'
Thanks in advance.

As much as people will probably recommend regular expression I'd say use explode().
Explode splits the string up in several substrings using any delimiter.
In this case I use ' <' as a delimiter to immediately strip the whitespace between the name and e-mail.
$split = explode(' <', $email_string);
$name = $split[0];
$email = rtrim($split[1], '>');
rtrim() will trim the '>' character from the end of the string.

Using explode + list:
$email_string = 'Aslam Doctor <aslam.doctor#gmail.com>';
list($name, $email) = explode(' <', trim($email_string, '> '));

If you can use the IMAP extension, the imap_rfc822_parse_adrlist function is all you need.
/via https://stackoverflow.com/a/3638433/204774

text variable have one paragraph. two emails are included there. using extract_emails_from_string() function we extracts those mails from that paragraph.
preg_match_all function will return all matching strings with the regular expression from inputs.
function extract_emails_from_string($string){
preg_match_all("/[\._a-zA-Z0-9-]+#[\._a-zA-Z0-9-]+/i", $string, $matches);
return $matches[0];
}
$text = "Please be sure to answer the Please arun1#email.com be sure to answer the Please be sure to answer the Please be sure to answer the Please be sure to answer the Please be sure to answer the Please be sure to answer the arun#email.com";
$emails = extract_emails_from_string($text);
print(implode("\n", $emails));

This is what I use - works for email addresses with and without the angle bracket formatting. Because we are searching from right to left, this also works for those weird instances where the name segment actually contains the < character:
$email = 'Aslam Doctor <aslam.doctor#gmail.com>';
$address = trim(substr($email, strrpos($email, '<')), '<>');

Related

Extract variables with preg match

Hi i am having an issue in trying to extract variables using preg replace .I guess i am messing with the delimiters or just doing it wrong
Subject
'file': 'EoWviKqVizQ,end=1384596943/data=B262F941/speed=375k/2305873_hd.flv',
I need to extract
end=1384596943/data=B262F941/speed=375k/1234_hd.flv
This is basically the string after the comma in between the single quotes.
My attempts
preg_match('#'file':'(.*)'#',$input , $matches)
preg_match("#'file':'(.*)'#",$input , $matches)
Hope someone can help me out
Regards
Just do this:
$input = "'file': 'EoWviKqVizQ,end=1384596943/data=B262F941/speed=375k/2305873_hd.flv',";
$mypart = preg_replace("/^'file': '[^,]+,/", "", $input); // strip first part, i.e., "'file': 'EoWviKqVizQ,"
$mypart = preg_replace("/',\s*$/", "", $mypart); // strip last part, i.e., "',"
echo $mypart;
EDITED based on OP feedback (replaced initial [^']+ with file to match only lines starting with 'file', etc.

PHP Remove Value of String with Variable Numbers

Basically from a database I am getting data that is formatted like this nameofproject101 Now this could continue to increase so eventually it could be nameofproject1001 my question is how can I trim off the number and just get the name of the project. I thought about using substr but since I dont know the length always I cant really do that. Since the numbers differ I dont think I can use str_replace is there any way to accomplish this?
It sounds like something is way off about your database scheme. You should probably try to do refactor/normalize your scheme.
But in the meantime, you can use rtrim() to trim all numbers off of the right side.
$val = rtrim($val, '0123456789');
Examples
Input Output
nameofproject1001 nameofproject
nameofproject nameofproject
n4me0fproj3ct1001 n4me0fproj3ct
for string like, project12V123, It is better to do this
$text = `project12V123`;
$text = preg_replace('/([\w]+)([^0-9])([0-9])+$/', '$1$2', $text);
Will return:
Project12V
or use rtrim:
$text = rtrim($text,'0123456789');
You should definitely use regular expressions:
$fullname = "nameofproject101";
preg_match("/([a-z]+)([0-9]+)/i", $fullname, $matches);
$name = $matches[1];
$number = $matches[2];
echo "'$fullname' is '$name' followed by '$number'";
preg_replace('/[^a-z]/i', '', $string);

Preg_match, Replace and back to string

sorry but i cant solve my problem, you know , Im a noob.
I need to find something in string with preg_match.. then replace it with new word using preg_replace, that's ok, but I don't understand how to put replaced word back to that string.
This is what I got
$text ='zda i "zda"';
preg_match('/"(\w*)"/', $text);
$najit = '/zda/';
$nahradit = 'zda';
$o = '/zda/';
$a = 'if';
$ahoj = preg_replace($najit, $nahradit, $match[1]);
Please, can you help me once again?
You can use e.g. the following code utilizing negative lookarounds to accomplish what you want:
$newtext = preg_replace('/(?<!")zda|zda(?!")/', 'if', $text)
It will replace any occurence of zda which is not enclosed in quotes on both sides (i.e. in U"Vzda"W the zda will be replaced because it is not enclosed directly into quotes).

Regex Get Email handle from Email Address

I have an email address that could either be
$email = "x#example.com"; or $email="Johnny <x#example.com>"
I want to get
$handle = "x"; for either version of the $email.
How can this be done in PHP (assuming regex). I'm not so good at regex.
Thanks in advance
Use the regex <?([^<]+?)# then get the result from $matches[1].
Here's what it does:
<? matches an optional <.
[^<]+? does a non-greedy match of one or more characters that are not ^ or <.
# matches the # in the email address.
A non-greedy match makes the resulting match the shortest necessary for the regex to match. This prevents running past the #.
Rubular: http://www.rubular.com/r/bntNa8YVZt
Here is a complete PHP solution based on marcog's answer
function extract_email($email_string) {
preg_match("/<?([^<]+?)#([^>]+?)>?$/", $email_string, $matches);
return $matches[1] . "#" . $matches[2];
}
echo extract_email("ice.cream.bob#gmail.com"); // outputs ice.cream.bob#gmail.com
echo extract_email("Ice Cream Bob <ice.cream.bob#gmail.com>"); // outputs ice.cream.bob#gmail.com
Just search the string using this basic email-finding regex: \b[A-Z0-9._%+-]+#[A-Z0-9.-]+.[A-Z]{2,4}\b
It will match any email in any text, and in your first string it will match the whole string, and in the second, only the part of the string that is e-mail.
To quickly learn regexp this is the best place: http://www.regular-expressions.info
$email = 'x#gmail.com';
preg_match('/([a-zA-Z0-9\-\._\+]+#[a-z0-9A-Z\-\._]+\.[a-zA-Z]+)/', $email, $regex);
$handle = array_shift(explode('#', $regex[1]));
Try that (Not tested)

Does anyone have a PHP snippet of code for grabbing the first "sentence" in a string?

If I have a description like:
"We prefer questions that can be answered, not just discussed. Provide details. Write clearly and simply."
And all I want is:
"We prefer questions that can be answered, not just discussed."
I figure I would search for a regular expression, like "[.!\?]", determine the strpos and then do a substr from the main string, but I imagine it's a common thing to do, so hoping someone has a snippet lying around.
A slightly more costly expression, however will be more adaptable if you wish to select multiple types of punctuation as sentence terminators.
$sentence = preg_replace('/([^?!.]*.).*/', '\\1', $string);
Find termination characters followed by a space
$sentence = preg_replace('/(.*?[?!.](?=\s|$)).*/', '\\1', $string);
<?php
$text = "We prefer questions that can be answered, not just discussed. Provide details. Write clearly and simply.";
$array = explode('.',$text);
$text = $array[0];
?>
My previous regex seemed to work in the tester but not in actual PHP. I have edited this answer to provide full, working PHP code, and an improved regex.
$string = 'A simple test!';
var_dump(get_first_sentence($string));
$string = 'A simple test without a character to end the sentence';
var_dump(get_first_sentence($string));
$string = '... But what about me?';
var_dump(get_first_sentence($string));
$string = 'We at StackOverflow.com prefer prices below US$ 7.50. Really, we do.';
var_dump(get_first_sentence($string));
$string = 'This will probably break after this pause .... or won\'t it?';
var_dump(get_first_sentence($string));
function get_first_sentence($string) {
$array = preg_split('/(^.*\w+.*[\.\?!][\s])/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
// You might want to count() but I chose not to, just add
return trim($array[0] . $array[1]);
}
Try this:
$content = "My name is Younas. I live on the pakistan. My email is **fromyounas#gmail.com** and skype name is "**fromyounas**". I loved to work in **IOS development** and website development . ";
$dot = ".";
//find first dot position
$position = stripos ($content, $dot);
//if there's a dot in our soruce text do
if($position) {
//prepare offset
$offset = $position + 1;
//find second dot using offset
$position2 = stripos ($content, $dot, $offset);
$result = substr($content, 0, $position2);
//add a dot
echo $result . '.';
}
Output is:
My name is Younas. I live on the pakistan.
current(explode(".",$input));
I'd probably use any of the multitudes of substring/string-split functions in PHP (some mentioned here already).
But also look for ". " OR ".\n" (and possibly ".\n\r") instead of just ".". Just in case for whatever reason, the sentence contains a period that isn't followed by a space. I think it will harden the likelihood of you getting genuine results.
Example, searching for just "." on:
"I like stackoverflow.com."
Will get you:
"I like stackoverflow."
When really, I'm sure you'd prefer:
"I like stackoverflow.com."
And once you have that basic search, you'll probably come across one or two occasions where it may miss something. Tune as you run with it!
Try this:
reset(explode('.', $s, 2));

Categories