Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!doctype html>
- <html class="no-js" lang="">
- <head>
- <meta charset="utf-8">
- <meta http-equiv="x-ua-compatible" content="ie=edge">
- <title></title>
- <meta name="description" content="">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
- <link rel="apple-touch-icon" href="apple-touch-icon.png">
- <!-- Modernizr -->
- <script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js"></script>
- <!-- BootStrap 4 -->
- <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
- <style>
- code {
- background: #eee;
- padding: 1em 0.5em;
- border-radius: 4px;
- margin-bottom: 2em;
- display: block;
- }
- </style>
- </head>
- <body>
- <!--[if lt IE 8]>
- <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
- <![endif]-->
- <!-- Add your site or application content here -->
- <main class="container">
- <section class='test-pen'>
- <h2 class='test-pen__title'>1.2 Extracting Substrings</h2>
- <h3 class='test-pen__subtitle'>Problem</h3>
- <p>You want to extract part of a string, starting at a particular place in the string. For example, you want the first eight characters of a username entered into a form.</p>
- <form action='<?=$_SERVER['PHP_SELF'];?>' method='POST' class='form'>
- <div class='form-group'>
- <label for="username">Username:</label>
- <input type="text" class="form-control" name="username" required>
- </div>
- <div class="form-group">
- <label for="pswd">Password:</label>
- <input type="password" class="form-control" name="pswd" required>
- </div>
- <div class="form-group">
- <input type="submit" class="form-control" value="Submit">
- </div>
- </form>
- <?php
- // get the first 8 character substring from the input username
- if ( isset( $_POST['username'] ) ) $username = $_POST['username'];
- if ( isset( $username ) ) $substring = substr( $username, 0, 8 );
- if ( !empty( $substring ) ):
- ?>
- <code class='code'>
- the first 8 characters of the username passed to the form is: <?php echo $substring; ?>
- </code>
- <?php endif; ?>
- <h3>Leaving out $start from substr()</h3>
- <p>If you leave out $length, substr() returns the string from $start to the end of the original string, as shown:</p>
- <code>
- <?php
- print substr('watch out for that tree', 17);
- ?>
- </code>
- <h3>$start is larger than $length</h3>
- <p>If $start is bigger than the length of the string, substr() returns false.</p>
- <code>
- <?php
- $string = 'Dog';
- $start = strlen($string) + 2;
- $length = strlen($string);
- if ( substr($string, $start, $length) === FALSE ) {
- echo '$start variable is longer than the $length variable.';
- }
- ?>
- </code>
- <h3>$start is negative</h3>
- <p>If $start is negative, substr() counts back from the end of the string to determine where your substring starts, as shown:</p>
- <code>
- <?php
- print substr( 'watch out for that tree', -6 ) . PHP_EOL;
- print substr( 'watch out for that tree', -17, 5 ) . PHP_EOL;
- ?>
- </code>
- </section>
- <section>
- <h2>Replacing substrings</h2>
- <h3>Problem</h3>
- <p>You want to replace a substring with a different string. For example, you want to obscure all but the last four digits of a credit card number before printing it.</p>
- <code>
- <?php
- define('BREAK_TAG', "<br>");
- $cc = '4266 8414 2232 8218';
- function obscure_cc_last_4( $cc_num ) {
- /*
- ** substr_replace( $old_str, $new_substr, $start, $length )
- */
- return substr_replace( $cc_num, '**** ', -4 );
- }
- echo obscure_cc_last_4($cc) . BREAK_TAG;
- function obscure_cc_all_but_last_4( $cc_num ) {
- return substr_replace( $cc_num, '**** ', 0, strlen($cc_num) - 4 );
- }
- print obscure_cc_all_but_last_4($cc);
- ?>
- </code>
- <h3>Discussion</h3>
- <p>Without the $length argument, substr_replace() replaces everything from $start to the end of the string. If $length is specified, only that many characters are replaced:</p>
- <code>
- <?php
- $my_pet = 'My pet is a blue dog.';
- print substr_replace( $my_pet, 'fish.', strpos($my_pet, 'd') );
- echo BREAK_TAG;
- print substr_replace( $my_pet, 'green', strpos($my_pet, 'b'), 4 ); // only replaces up to 4 chars from $start of $old_str (then continues w rest of $old_str)
- $credit_card = '4111 1111 1111 1111';
- echo BREAK_TAG;
- print substr_replace( $credit_card, 'xxxx ', 0, strlen($credit_card) - 4 ); // replace everything at start with new string, except the last 4
- ?>
- </code>
- <p>The function substr_replace() is useful when you’ve got text that’s too big to display all at once, and you want to display some of the text with a link to the rest. Example 1-15 displays the first 25 characters of a message with an ellipsis after it as a link to a page that displays more text.</p>
- <code>
- <?php
- /*
- ** Objective: Understand DB operations and apis to begin planning databases and data
- ** structures within applications using PHP. Think about how to manipulate
- ** data and why it would be useful to users thjat call the db within said app.
- */
- function connect_to_db( $servername, $username, $password, $dbname ) {
- if (! isset($servername) ) $servername = NULL;
- if (! isset($username) ) $username = NULL;
- if (! isset($password) ) $password = NULL;
- if (! isset($dbname) ) $dbname = NULL;
- // Create connection
- $conn = new mysqli($servername, $username, $password);
- // Check connection
- if ($conn->connect_error) {
- die("Connection failed: " . $conn->connect_error);
- }
- echo "Connected successfully" . BREAK_TAG;
- return $conn;
- }
- function disconnect( $conn ) {
- $conn->close();
- echo "Disconnected from database" . BREAK_TAG;
- }
- function select_db($conn, $name) {
- mysqli_select_db($conn, $name) or die(mysql_error() . 'ln:160');
- }
- function insert_message( $conn, $id, $message ) {
- $query = "INSERT INTO messages (`id`, `message`) VALUES ('$id', '$message')";
- if (mysqli_query($conn, $query) == TRUE)
- echo "Query successful!" . BREAK_TAG;
- else
- die(mysqli_error($conn));
- }
- function render_message_for_user($conn, $id) {
- $result = $conn->query("SELECT id,message FROM messages WHERE id=$id") or die();
- printf("Select returned %d rows.\n", $result->num_rows);
- // TODO: this shit...
- //$message = $conn->query("SELECT message FROM messages WHERE id=$id");
- // $message_result = mysql_fetch_object($message);
- ?>
- <code>
- <?= $data; ?>
- </code>
- <table class="table">
- <thead>
- <tr>
- <th scope="col">ID:</th>
- <th scope="col">MESSAGE:</th>
- </tr>
- </thead>
- <tbody>
- <tr>
- <th scope="row"><?= $id; ?></th>
- </tr>
- <tr>
- <th scope="row"><?= $message; ?></th>
- </tr>
- </tbody>
- </table>
- <?php
- }
- $mysqli = connect_to_db( 'localhost', 'root', 'NEYybep7fzu3$', 'test' );
- select_db($mysqli, 'test');
- if ( $mysqli->connect_errno )
- printf( "Connection Failure: %s" . BREAK_TAG, $mysqli->connect_error );
- else {
- $msg = "ER AIN\'T NO TIME FOR DISCUSSION! THE ART OF WAR IS MY THEORY I LOVE IT!";
- insert_message( $mysqli, 1, $msg );
- render_message_for_user($mysqli, 1);
- }
- disconnect($mysqli);
- ?>
- </code>
- </section>
- </main>
- <script src="http://code.jquery.com/jquery-1.12.4.min.js"></script>
- <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
- <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.12.4.min.js"><\/script>')</script>
- <!-- Google Analytics: change UA-XXXXX-Y to be your site's ID. -->
- <script>
- window.ga=function(){ga.q.push(arguments)};ga.q=[];ga.l=+new Date;
- ga('create','UA-XXXXX-Y','auto');ga('send','pageview')
- </script>
- <script src="https://www.google-analytics.com/analytics.js" async defer></script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement