PDA

View Full Version : ereg Help for A Beginner



okason
28 Sep 2010, 04:57 PM
Hello all, I am taking a class on PHP and I need help with the question below


Use the ereg() function and regular expressions to find the web address http://www.google.com/
in the following string and echoes it to the browser. Below is the string:
<a href="http://www.google.com/">Link to Google</a>
Do not use the complete url string "http://www.google.com/" in your search expression.

You must use some combination of search expressions such as a-z, A-Z, etc.
Be careful to account for the double-quotes in the string.
You will probably need to use the backslash character as an
scape character in order to process the string properly.



Here is my attempt to answer the question but for some reason the string variable $givenurl is not grabbing the whole string, so I need help particularly with how to properly escape the string <a href="http://www.google.com/">Link to Google</a>

<?php
$givenurl = "<a href\=\"http:\/\/www.google.com/\">Link to Google</a>";

if ($givenurl !== "")

{
ereg("[a-zA-Z0-9_]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]", $givenurl, $newurl);
echo $newnurl;
}

else

echo "No Url found";


?>

tivy
30 Sep 2010, 11:54 AM
As far as I can see, your regex pattern shouldn't match that candidate string at all because there's no "@" symbol in the candidate string. In fact your regex pattern looks like a rudimentary email detection pattern. Try this instead:

http:\/\/(www.)?[a-zA-Z0-9\-_.]+\.[a-zA-Z]{3,4}

Tested and verified with following code.



$haystack = "<a href=\"http://www.google.com\">Link to Google</a>";
ereg("http:\/\/(www.)?[a-zA-Z0-9\-_.]+\.[a-zA-Z]{3,4}", $haystack, $result);

if( $result )
echo $result[0];
else
echo "Fail!";