Thursday, May 5, 2011

PHP Interview Questions 6-10

7. How can we extract string ‘techinterviews.com ‘ from a string ‘http://www.techinterviews.com’ using regular expression of PHP?


    Type 1

    '<'?php
    preg_match
    ('@^(?:http://)?([^/]+)@i',
    "http://www.php.net/index.html",$matches);
    $host=$matches[1];


    preg_match('/[^.]+\.[^.]+$/', $host, $matches);
    echo
    "domain name is: {$matches[0]}\n";
    ?>

type 2

    '<'?php

    preg_match ( "/^(http:\/\/www\.)?([^\/]+)/i" , "http://www.jacksiva.blogpot.com/siva/jack/index.html" , $matches );

    echo $matches [ 2 ].'
    ';
    //echo $host -> jacksiva.blogspot.com

    ?>

    type 3

    preg_match ( "/^(http:\/\/)?([^\/]+)/i" , "http://www.jacksiva.blogpot.com/siva/index.html" , $matches );

    $host = $matches [ 2 ]; //echo $host -> www.jacksiva.blogspot.com

    preg_match ( "/[^.]+\.[^.]+\.[^.]+$/i" , $host, $matches );

    echo $host2 = $matches[0];

    ?>

    output: php.net

    note:

    asterisk ("*") has the meaning "some or none" or "zero or more."

    The plus-sign ("+") means "one or more times"

    The question-mark ("?") means "zero or one times."


    email validation:

    '<'?php
    if (isset($_POST['submit'])){
    $emailfield=$_POST['emailfield'];
    echo $emailfield;
    $okay=
    preg_match('/^[A-z0-9_\-\.]+[@][A-z0-9_\-]+([.][A-z0-9_\-])+[A-z]{2,4}$/',$emailfield);
    if($okay){
    echo "E-mail is validated";
    }else{
    echo"E-mail is incorrect";
    }
    }
    ?>
    '<'form method="POST" action="email.php">
    E-mail address: '<'input type="text" name="emailfield">
    '<'input type="submit" name="submit" value="Validate">

8.How can we create a database using PHP and mysql?
$con = mysql_connect("localhost","peter","abc123");
mysql_query("CREATE DATABASE my_db",$con);

9. What are the differences between require and include, include_once?

    include();--> include the file, but in case of file missing
    throws a warning and continues execution of code of next line.
    require();; require also includes the file but in case of file missing throws an fatal error
    and stop the execution of
    the code of next line.
    include_once();if same file was included first it will not include the file another time.
    but include( ) using more than one time.

    10. Can we use include (”techinterviews.php”) two times in a PHP page “makeit.PHP”?

    Yes. To use include () two time is possible.



No comments:

Post a Comment