I have a string like
<?php
$string = "
hello aaa#aaa.com , you are the best.
this email bbb#bbb.com my be fake
(i have question to ccc#ccc.com)
that's all";
?>
I want to detect the last email (what ever number of email equal any number) for example: ccc#ccc.com
<?php
function getLastEmail($_String)
{
$_RegVariables = "/[\._a-zA-Z0-9-]+#[\._a-zA-Z0-9-]+/i";
if (preg_match_all($_RegVariables, $_String, $_Matches))
{
$_Result = array();
$_RegResult = array_combine($_Matches[0], $_Matches[0]);
foreach($_RegResult as $key=>$value)
{
$_Result[] = $key;
}
}
return $_Result[ sizeOf( $_Result )-1 ];
}
$string = "
hello aaa#aaa.com , you are the best.
this email bbb#bbb.com my be fake
(i have question to ccc#ccc.com)
that's all";
$lastemail = getLastEmail($string);
echo $lastemail;
?>
Now $lastemail is ccc#ccc.com
Good luck.
Here is a quick solution, you may have to do some string clean up to remove characters (like '(' or ')') but this works if those aren't present.
<?php
$string = "
hello aaa#aaa.com , you are the best.
this email bbb#bbb.com my be fake
i have question to ccc#ccc.com
that's all";
$a = explode(' ', $string);
$aEmail = array();
foreach($a as $svar=>$sval)
{
if(preg_match('/^[^#]+#[a-zA-Z0-9._-]+\.[a-zA-Z]+$/', $a[$svar]))
$aEmail[] .= $a[$svar];
}
$sEmail_Last = array_pop($aEmail);
echo $sEmail_Last; // echo ccc#ccc.com
?>
Related
I have just learnt some basic skill for html and php and I hope someone could help me .
I had created a html file(a.html) with a form which allow students to input their name, student id, class, and class number .
Then, I created a php file(a.php) to saved the information from a.html into the info.txt file in the following format:
name1,id1,classA,1
name2,id2,classB,24
name3,id3,classA,15
and so on (The above part have been completed with no problem) .
After that I have created another html file(b.html), which require user to enter their name and id in the form.
For example, if the user input name2 and id2 in the form, then the php file(b.php) will print the result:
Class: classB
Class Number: 24
I have no idea on how to match both name and id at the same time in the txt file and return the result in b.php
example data:
name1,id1,classA,1
name2,id2,classB,24
name3,id3,classA,15
<?php
$name2 = $_POST['name2'];
$id2 = $_POST['id2'];
$data = file_get_contents('info.txt');
if($name2!='')
$konum = strpos($data, $name2);
elseif($id2!='')
$konum = strpos($data, $id2);
if($konum!==false){
$end = strpos($data, "\n", $konum);
$start = strrpos($data, "\n", (0-$end));
$row_string = substr($data, $start, ($end - $start));
$row = explode(",",$row_string);
echo 'Class : '.$row[2].'<br />';
echo 'Number : '.$row[3].'<br />';
}
?>
Iterate through lines until you find your match. Example:
<?php
$csv=<<<CSV
John,1,A
Jane,2,B
Joe,3,C
CSV;
$data = array_map('str_getcsv', explode("\n", $csv));
$get_name = function($number, $letter) use ($data) {
foreach($data as $row)
if($row[1] == $number && $row[2] == $letter)
return $row[0];
};
echo $get_name('3', 'C');
Output:
Joe
You could use some simple regex. For example:
<?php
$search_name = (isset($_POST['name'])) ? $_POST['name'] : exit('Name input required.');
$search_id = (isset($_POST['id'])) ? $_POST['id'] : exit('ID input required.');
// First we load the data of info.txt
$data = file_get_contents('info.txt');
// Then we create a array of lines
$lines = preg_split('#\\n#', $data);
// Now we can loop the lines
foreach($lines as $line){
// Now we split the line into parts using the , seperator
$line_parts = preg_split('#\,#', $line);
// $line_parts[0] contains the name, $line_parts[1] contains the id
if($line_parts[0] == $search_name && $line_parts[1] == $search_id){
echo 'Class: '.$line_parts[2].'<br>';
echo 'Class Number: '.$line_parts[3];
// No need to execute the script any further.
break;
}
}
You can run this. I think it is what you need. Also if you use post you can change get to post.
<?php
$name = $_GET['name'];
$id = $_GET['id'];
$students = fopen('info.txt', 'r');
echo "<pre>";
// read each line of the file one by one
while( $student = fgets($students) ) {
// split the file and create an array using the ',' delimiter
$student_attrs = explode(',',$student);
// first element of the array is the user name and second the id
if($student_attrs[0]==$name && $student_attrs[1]==$id){
$result = $student_attrs;
// stop the loop when it is found
break;
}
}
fclose($students);
echo "Class: ".$result[2]."\n";
echo "Class Number: ".$result[3]."\n";
echo "</pre>";
strpos can help you find a match in your file. This script assumes you used line feed characters to separate the lines in your text file, and that each name/id pairing is unique in the file.
if ($_POST) {
$str = $_POST["name"] . "," . $_POST["id"];
$file = file_get_contents("info.txt");
$data = explode("\n", $file);
$result = array();
$length = count($data);
$i = 0;
do {
$match = strpos($data[$i], $str, 0);
if ($match === 0) {
$result = explode(",", $data[$i]);
}
} while (!$result && (++$i < $length));
if ($result) {
print "Class: " . $result[2] . "<br />" . "Class Number: " . $result[3];
} else {
print "Not found";
}
}
I need to find out if there are any redundant words in string or not .Is there any function that can provide me result in true/false.
Example:
$str = "Hey! How are you";
$result = redundant($str);
echo $result ; //result should be 0 or false
But for :
$str = "Hey! How are are you";
$result = redundant($str);
echo $result ; //result should be 1 or true
Thank you
You could use explode to generate an array containing all words in your string:
$array = explode(" ", $str);
Than you could prove if the arrays contains duplicates with the function provided in this answer:
https://stackoverflow.com/a/3145660/5420511
I think this is what you are trying to do, this splits on punctuation marks or whitespaces. The commented out lines can be used if you want the duplicated words:
$str = "Hey! How are are you?";
$output = redundant($str);
echo $output;
function redundant($string){
$words = preg_split('/[[:punct:]\s]+/', $string);
if(max(array_count_values($words)) > 1) {
return 1;
} else {
return 0;
}
//foreach(array_count_values($words) as $word => $count) {
// if($count > 1) {
// echo '"' . $word . '" is in the string more than once';
// }
//}
}
References:
http://php.net/manual/en/function.array-count-values.php
http://php.net/manual/en/function.max.php
http://php.net/manual/en/function.preg-split.php
Regex Demo: https://regex101.com/r/iH0eA6/1
i am trying to determine the best way to determine whether an email address is an outlook or hotmail address.
i therefore need to collect the values after the #
i.e
testemail#outlook.com
caputure the #
however this will not work in all instance as
this email address is valid:
"foo\#bar"#iana.org
i read that a solution could be to explode it, i.e:
$string = "user#domain.com";
$explode = explode("#",$string);
array_pop($explode);
$newstring = join('#', $explode);
echo $newstring;
this solution seems bit long and only captures the first values
would really appreciate some help
if You explode This :
$string = "user#domain.com";
$explode = explode("#",$string);
it Will be :
$explode[0] = user
$explode[1] = domain.com
try to use array_reverse() ti pick the last value of email:
<?php
$email='exa#mple#hotmail.com';
$explode_email=explode('#',$email);
$reversed_array=array_reverse($explode_email);
$mailserver=explode('.',$reversed_array[0]);
echo $mailserver[0];
?>
You could always just keep it simple and test if either value exists in the string using strpos() or stripos().
if ( FALSE !== stripos($string, 'outlook') {
// outlook exists in the string
}
if ( FALSE !== stripos($string, 'hotmail') {
// hotmail exists in the string
}
I hope this will be easy for you to understand.
<?php
$emailAddress = 'mailbox#hotmail.com'; //Email Address
$emailStringArray = explode('#',$emailAddress); // take apart the email string.
$host = $emailStringArray[1]; //last string after # . $emailStringArray[0] = Mailbox & $emailStringArray[1] = host
if($host == "hotmail.com" || $host == "outlook.com"){
//matches to outlook.com or hotmail.com
}
else{
//Does not match to outlook.com or hotmail.com
}
I would recommend matching with a regular expression.
if (preg_match("/\#hotmail.com$/", $email)) {
echo "on hotmail";
} else if (preg_match("/\#outlook.com$/", $email)) {
echo "on outlook";
} else {
echo "different domain";
}
Additionally, if you want to capture full domain to variable, you can do it like this:
$matches = [];
if (preg_match("/^.*\#([\w\.]+)$/", $email, $matches)) {
echo "Domain: " . $matches[1];
} else {
echo "not a valid email address.";
}
Try this :
$emailAddress = 'example\#sometext\#someothertext#hotmail.com';
$explodedEmail = explode('#', $emailAddress);
$emailServerHostName = end($explodedEmail);
$emailServerNameExploded = explode('.', $emailServerHostName);
$emailServerName = $emailServerNameExploded[0];
echo $emailServerName;
I'd like to replace the numbers and email from the sentences.
Example
$message = "Hi this is john, my personal no is 1213456789 and my email address is john#gmail.com".
Output:
Hi this is john, my personal no is 1213456789 and my email address is john#gmail.com
I want the Output to be like this:
Output:
Hi this is john, my personal no is XXXXXXX789 and my email address is XXXX#gmail.com
But I'm currently getting like this :
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX#gmail.com
function which I'm using now
function numbers1($str)
{
if(($until = strpos($str, '#')) !== false)
{
$str = str_repeat('X', $until) . substr($str, $until);
}
}
Thanks in advance.
try preg_replace()
$str = "Hi this is john, my personal no is 1213456789 and my email address is john#gmail.com";
$replacements[1] = 'X';
$replacements[0] = 'XXXX#';
echo preg_replace(array('/[0-6]/', '/[ a-z]{0,4}+#/'), $replacements, $str);
output :- Hi this is john, my personal no is XXXXXXX789 and my email address is XXXX#gmail.com
$message = "Hi this is john, my personal no is 1213456789 and my email address is john#gmail.com";
$arr = explode(" ", $message);
foreach($arr as $key=>$val)
{
if(!preg_match ("/[^0-9]/", $val))
{
$val_new = "XXXXXXX".substr($val, -3);
$arr[$key] = $val_new;
}
else if(strpos($val, "#")>0)
{
$arr_email = explode("#", $val);
$arr_email[0] = "XXXX";
$val_new = implode("#", $arr_email);
$arr[$key] = $val_new;
}
}
$new_msg = implode(" ", $arr);
echo $new_msg;
UPDATE 2 :
$message = "Hi this is john, my personal no is 1213456789 and my email address is john#gmail.com";
$arr = explode(" ", $message);
foreach($arr as $key=>$val)
{
if(!preg_match ("/[^0-9]/", $val))
{
$val_new = "XXXXXXX".substr($val, -3);
$arr[$key] = $val_new;
}
else if(preg_match ("/^[a-z0-9_\+-]+(\.[a-z0-9_\+-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,4})$/", $val))
{
$arr_email = explode("#", $val);
$arr_email[0] = "XXXX";
$val_new = implode("#", $arr_email);
$arr[$key] = $val_new;
}
}
$new_msg = implode(" ", $arr);
echo $new_msg;
You're asking how to do this using jQuery, however your sample code is written in PHP. I'll answer your question with a PHP snippet as well.
The reason why your function isn't working is because you're replacing pretty much everything from the beginning of the string up to the position where the first '#' is found. Then you're adding as many 'X' as characters are until that position, followed by the rest of the string. To complicate things more, this won't work if two or more email addresses are found in your string.
This should do. You might need to tweak the regexes for both the phone numbers and the email addresses, though:
$message = "Hi this is john, my personal no is 1213456789 and my email address is john#gmail.com";
// get all phone numbers
preg_match('/\d{3,}/s', $message, $phones);
// get all email addresses
preg_match('/[a-z.-]+#[a-z.-]+/s', $message, $emails);
foreach ($phones as $phone)
{
$message = str_replace($phone, str_repeat('X', strlen($phone) - 3) . substr($phone, -3), $message);
}
foreach ($emails as $email)
{
$parts = explode('#', $email);
$message = str_replace($email, str_repeat('X', strlen($parts[0])) . '#' . $parts[1], $message);
}
// Hi this is john, my personal no is XXXXXXX789 and my email address is XXXX#gmail.com
echo $message;
If I have a string that contains a url (for examples sake, we'll call it $url) such as;
$url = "Here is a funny site http://www.tunyurl.com/34934";
How do i remove the URL from the string?
Difficulty is, urls might also show up without the http://, such as ;
$url = "Here is another funny site www.tinyurl.com/55555";
There is no HTML present. How would i start a search if http or www exists, then remove the text/numbers/symbols until the first space?
I re-read the question, here is a function that would work as intended:
function cleaner($url) {
$U = explode(' ',$url);
$W =array();
foreach ($U as $k => $u) {
if (stristr($u,'http') || (count(explode('.',$u)) > 1)) {
unset($U[$k]);
return cleaner( implode(' ',$U));
}
}
return implode(' ',$U);
}
$url = "Here is another funny site www.tinyurl.com/55555 and http://www.tinyurl.com/55555 and img.hostingsite.com/badpic.jpg";
echo "Cleaned: " . cleaner($url);
Edit #2/#3 (I must be bored). Here is a version that verifies there is a TLD within the URL:
function containsTLD($string) {
preg_match(
"/(AC($|\/)|\.AD($|\/)|\.AE($|\/)|\.AERO($|\/)|\.AF($|\/)|\.AG($|\/)|\.AI($|\/)|\.AL($|\/)|\.AM($|\/)|\.AN($|\/)|\.AO($|\/)|\.AQ($|\/)|\.AR($|\/)|\.ARPA($|\/)|\.AS($|\/)|\.ASIA($|\/)|\.AT($|\/)|\.AU($|\/)|\.AW($|\/)|\.AX($|\/)|\.AZ($|\/)|\.BA($|\/)|\.BB($|\/)|\.BD($|\/)|\.BE($|\/)|\.BF($|\/)|\.BG($|\/)|\.BH($|\/)|\.BI($|\/)|\.BIZ($|\/)|\.BJ($|\/)|\.BM($|\/)|\.BN($|\/)|\.BO($|\/)|\.BR($|\/)|\.BS($|\/)|\.BT($|\/)|\.BV($|\/)|\.BW($|\/)|\.BY($|\/)|\.BZ($|\/)|\.CA($|\/)|\.CAT($|\/)|\.CC($|\/)|\.CD($|\/)|\.CF($|\/)|\.CG($|\/)|\.CH($|\/)|\.CI($|\/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.UK($|\/)|\.US($|\/)|\.UY($|\/)|\.UZ($|\/)|\.VA($|\/)|\.VC($|\/)|\.VE($|\/)|\.VG($|\/)|\.VI($|\/)|\.VN($|\/)|\.VU($|\/)|\.WF($|\/)|\.WS($|\/)|\.XN--0ZWM56D($|\/)|\.XN--11B5BS3A9AJ6G($|\/)|\.XN--80AKHBYKNJ4F($|\/)|\.XN--9T4B11YI5A($|\/)|\.XN--DEBA0AD($|\/)|\.XN--G6W251D($|\/)|\.XN--HGBK6AJ7F53BBA($|\/)|\.XN--HLCJ6AYA9ESC7A($|\/)|\.XN--JXALPDLP($|\/)|\.XN--KGBECHTV($|\/)|\.XN--ZCKZAH($|\/)|\.YE($|\/)|\.YT($|\/)|\.YU($|\/)|\.ZA($|\/)|\.ZM($|\/)|\.ZW)/i",
$string,
$M);
$has_tld = (count($M) > 0) ? true : false;
return $has_tld;
}
function cleaner($url) {
$U = explode(' ',$url);
$W =array();
foreach ($U as $k => $u) {
if (stristr($u,".")) { //only preg_match if there is a dot
if (containsTLD($u) === true) {
unset($U[$k]);
return cleaner( implode(' ',$U));
}
}
}
return implode(' ',$U);
}
$url = "Here is another funny site badurl.badone somesite.ca/worse.jpg but this badsite.com www.tinyurl.com/55555 and http://www.tinyurl.com/55555 and img.hostingsite.com/badpic.jpg";
echo "Cleaned: " . cleaner($url);
returns:
Cleaned: Here is another funny site badurl.badone but this and and
$string = preg_replace('/\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|$!:,.;]*[A-Z0-9+&##\/%=~_|$]/i', '', $string);
Parsing text for URLs is hard and looking for pre-existing, heavily tested code that already does this for you would be better than writing your own code and missing edge cases. For example, I would take a look at the process in Django's urlize, which wraps URLs in anchors. You could port it over to PHP, and--instead of wrapping URLs in an anchor--just delete them from the text.
thanks mike,
update a bit, it return notice error,
'/\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|$!:,.;]*[A-Z0-9+&##\/%=~_|$]/i'
$string = preg_replace('/\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|$!:,.;]*[A-Z0-9+&##\/%=~_|$]/i', '', $string);
$url = "Here is a funny site http://www.tunyurl.com/34934";
$replace = 'http www .com .org .net';
$with = '';
$clean_url = clean($url,$replace,$with);
echo $clean_url;
function clean($url,$replace,$with) {
$replace = explode(" ",$replace);
$new_string = '';
$check = explode(" ",$url);
foreach($check AS $key => $value) {
foreach($replace AS $key2 => $value2 ) {
if (-1 < strpos( strtolower($value), strtolower($value2) ) ) {
$value = $with;
break;
}
}
$new_string .= " ".$value;
}
return $new_string;
}
You would need to write a regular expression to extract out the urls.