PHP & MySQL (MM) Chapter 2 Question (facebook)

Missing MAnual - PHP & MySQL Chapter2 - What are more 'if' options? Say the person enters 'facebook.com/john.smith.9979 but does not enter "http://" and another doesn't enter "http://www." How do I add more complete 'if' corrections? The book gives two options assuming that someone would leave out facebook.com. It's more likely they would leave off the http and/or the www and without either there can be no link.
1 person has
this question
+1
Reply
  • Hi John-

    Right now, the condition would cover the case where facebook.com is left out, but also where www or http://www are left out. Here's the relevant code:

    // Make sure they have facebook.com as part of the URL
    $position = strpos($facebook_url, "facebook.com");
    if ($position === false) {
    $facebook_url = "http://www.facebook.com/". $facebook_url;
    }

    This checks if facebook.com exists within $facebook_url. So if $facebook_url is "http://www.facebook.com" or "http://facebook.com" or "facebook.com" would all result in $position having a value, and then the if condition would be left alone.

    I assume you're wanting to make sure that http:// is added before the string in a case like "facebook.com/john.smith.9979"? You could do something like this:

    // Make sure they have a facebook domain prefix
    $position = strpos($facebook_url, "facebook.com");
    if ($position === false) {
    $facebook_url = "http://www.facebook.com/". $facebook_url;
    }
    // Now make sure http:// is prefixed for linking
    $position = strpos($facebook_url, "http://");
    if ($position === false) {
    $facebook_url = "http://" . $facebook_url;
    }

    Further, you really won't ever have a case where that second if is true when the first if is also true. In other words, if your code goes through the first if condition, it will have already added http://, so you could improve this:

    // Make sure they have a facebook domain prefix
    $position = strpos($facebook_url, "facebook.com");
    if ($position === false) {
    $facebook_url = "http://www.facebook.com/". $facebook_url;
    } else {
    // Now make sure http:// is prefixed for linking
    $position = strpos($facebook_url, "http://");
    if ($position === false) {
    $facebook_url = "http://" . $facebook_url;
    }
    }

    That way, if the first if executes, the second one never does.

    Now... I opened this response with saying this is the most "direct" answer. For a better, more flexible answer, you should keep reading until you hit Chapter 5 (Chapter 6 in the 2nd edition), which focus on Regular Expressions. You'll find those give you a LOT more tools to help with this sort of thing.

    -Brett
  • (some HTML allowed)
    How does this make you feel?
    Add Image
    I'm

    e.g. happy, confident, thankful, excited indifferent, undecided, unconcerned sad, anxious, confused, frustrated kidding, amused, unsure, silly