How can we extract string 'abc.com ' from a string http://info@abc.com using regular expression of php?How can we extract string "abc.com" from a string "mailto:info@abc.com ?subject= Feedback" using regular expression of PHP? ~ Interview Questions & Answers

Sunday, February 3, 2008

How can we extract string 'abc.com ' from a string http://info@abc.com using regular expression of php?

We can use the preg_match() function with "/.*@(.*)$/" as the regular expression pattern.
For example:
preg_match("/.*@(.*)$/","http://info@abc.com",$data);
echo $data[1];

How can we extract string "abc.com" from a string "mailto:info@abc.com ?subject= Feedback" using regular expression of PHP?

$text = "mailto:info@abc.com?subject=Feedback";
preg_match('|.*@([^?]*)|', $text, $output);
echo $output[1];
Note that the second index of $output, $output[1], gives the match, not the first one, $output[0].