Skip to content

Instantly share code, notes, and snippets.

@recck
Created September 7, 2012 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save recck/3666716 to your computer and use it in GitHub Desktop.
Save recck/3666716 to your computer and use it in GitHub Desktop.
Week 3 - Day 5 - Playing with Strings
<?php
/**
* Programming in PHP
* Week 3 - Day 5
* Playing with Strings
**/
/**
* length of a string!
**/
$string = 'Programming in PHP';
// Get the length of a string
echo strlen($string); // 18
/**
* cases
**/
$awkwardString = 'pRoGrAmMiNg In PhP';
// Lowercase that string
echo strtolower($awkwardString); // programming in php
// Uppercase that string
echo strtoupper($awkwardString); // PROGRAMMING IN PHP
/**
* repeat a string!
**/
$shortString = 'apple ';
// Repeat it!
echo str_repeat($shortString, 5); // apple apple apple apple apple
/**
* reverse and shuffle a string!
**/
$palindrome = 'racecar';
$randomString = 'lemon lime soda';
// Reverse and check if it is a palindrome!
if( strrev($palindrome) == $palindrome ){
echo 'This word is a palindrome!';
}
// Shuffle a string!
echo str_shuffle($randomString); // example: lolemn emsdaio
/**
* print a substring of a string
**/
// using 'lemon lime soda'
$lime = substr($randomString, 6, 4); // string, position to start from, length of substring
echo $lime; // lime
/**
* find and/or get position of a substring within a string
**/
$position = strpos($randomString, 'lime'); // 6
if( $position !== FALSE ){
echo 'lime found at position ' . $position;
}else {
echo 'lime not found!';
}
/**
* find and replace a substring
**/
$replaced = str_replace('lemon', 'kiwi', $randomString); // search for this, replace with that, inside of this string
echo $replaced; // kiwi lime soda
/**
* wrap a long string every x characters
**/
$longString = 'This string can be really long if you wanted it to be!';
// split the string every 20 characters with a break
echo wordwrap($longString, 20, '<br/>');
/**
* OUTPUT:
* This string can be
really long if you
wanted it to be!
**/
// split a really long word
$longWord = 'Antidisestablishmentarianism';
echo wordwrap($longWord, 20, '<br/>'); // Antidisestablishmentarianism
// split the word!
echo wordwrap($longWord, 20, '<br/>', true);
/**
* OUTPUT:
* Antidisestablishment
arianism
**/
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment