1) Given some text find all valid email addresses in it.
$ret = array(); function isValidEmail($word) { $domain_parts = array(); $domain = ""; $components = explode("@", $word); if (count($components) != 2) { return false; } else { $domain = $components[1]; $domain_parts = explode(".", $domain); if (count($domain_parts) < 2) { return false; } } return true; } function findEmailAddresses($input) { $result = array(); if ((!$input) || empty($input)) { return $result; } $words = explode(" ", $input); foreach ($words as $word) { if (isValidEmail($word)) { $result[] = $word; } } return $result; } $str = "This valid@email.com is just a test abc@ when @pqr is abc@pqr.com."; $ret = findEmailAddresses($str); var_dump($ret);
2) Given some text and an array of keywords, find all the words in the text which are any combination of the keywords. The below is by sorting. But another way is by hashing the keyword.
<?php $ret = array(); function mysort($str) { $arr = str_split($str); sort($arr, SORT_STRING); return implode("",$arr); } function findCombinations($input, $keywords) { $result = array(); if ((!$input) || empty($input)) { return count($result); } foreach ($keywords as $keyword) { $sortedKeywords[] = mysort($keyword); } var_dump($sortedKeywords); $inputArr = explode(" ", $input); foreach ($inputArr as $word) { $sortedInput[] = mysort($word); } var_dump($sortedInput); foreach ($sortedInput as $sortedWord) { if (in_array($sortedWord, $sortedKeywords)) { $result[] = $sortedWord; } } return $result; } $str = "This valid@email.com the is eht just a test abc@ when @pqr is abc@pqr.com."; $keywords = array("het", "opo"); $ret = findCombinations($str, $keywords); var_dump($ret); ?>