PROWAREtech

articles » current » php » tips-and-tricks » page-1

PHP: Tips and Tricks - Page 1

Strings, dates and times.

Strings

Here Document (heredoc) Strings

Heredocs start with a <<< and a token of choice and end with the same token followed by a semicolon. The token is case sensitive.

Define a heredoc as follows:

<?php
	print <<< EXAMPLE
	How now brown cow.
		The so called "car"
			cost $25,999!
	EXAMPLE;
?>

Or:

<?php
	$cost = '$25,999';
	print <<< EXAMPLE
	How now brown cow.
		The so called "car"
			cost $cost!
	EXAMPLE;
?>

The output would be this:

How now brown cow.
	The so called "car"
		cost $25,999!

Heredocs is useful for printing HTML with interpolated variables because double quotes do not need to be escaped. For example:

<?php
	$url = 'http://www.prowaretech.com/';
	print <<< HTML
	<p><a href="$url">home page</a></p>
	HTML;
?>

Or concatenate to the end of the heredoc using the period making sure the semicolon is at the end:

<?php
	$url = 'http://www.prowaretech.com/';
	$html <<< HTML
	<p><a href="$url">home page</a>
	HTML.'</p>';
	print $html;
?>

Accessing String Characters

To access an individual character, or byte, in a string use the square brackets: print $str[2];

Finding a Substring

If needing to find a string within a string then use strpos().

<?php
	$pos = strpos('this is a needle in a haystack', 'needle');
	if ($pos !== false) {
		print "needle was found in the haystack at position $pos";
	}
?>

strpos() returns the first position of the substring or false if not found so first check for false using === or !==.

Selecting a Substring

Use substr() to select a substring.

<?php
	$string = 'this is a needle in a haystack';
	$start = 10;
	$length = 6;
	$substring = substr($string, $start, $length);
	print $substring;
?>

If the length is not specified then substr() returns the whole string from the start position.

<?php
	$string = 'this is a needle in a haystack';
	$start = 10;
	$substring = substr($string, $start);
	print $substring;
?>

If a negative start is specified then it starts from the end of the string and counts backwards.

<?php
	$string = 'this is a needle in a haystack';
	$start = -20;
	$substring = substr($string, $start);
	print $substring;
?>
<?php
	$string = 'this is a needle in a haystack';
	$start = -20;
	$substring = substr($string, $start, 6);
	print $substring;
?>

Replacing a Substring

To replace a substring with a new string value then use substr_replace(). Negative values work the same as with substr().

<?php
	$string = 'this is a needle in a haystack';
	$start = -20;
	$length = 6;
	$newstring = substr_replace($string, 'picked-pepper-eater', $start, $length);
	print $newstring;
?>

Reversing a String

Use strrev() to reverse a string.

<?php
	$string = 'How now brown cow';
	$string = strrev($string);
	print $string
?>

Lowercase

Use strtolower() to convert an entire string to lowercase.

<?php
	$string = 'HOW NOW BROWN COW';
	$string = strtolower($string);
	print $string;
?>

Uppercase

Use strtoupper() to convert an entire string to uppercase.

<?php
	$string = 'how now brown cow';
	$string = strtoupper($string);
	print $string;
?>

Use ucfirst() to capitalize the first word.

<?php
	$string = 'how now brown cow';
	$string = ucfirst($string);
	print $string;
?>

Use ucwords() to capitalize every word.

<?php
	$string = 'how now brown cow';
	$string = ucwords($string);
	print $string;
?>

Create a Random String

<?php
	function randomstring($length = 50, $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdedfghijklmnopqrstuvwxyz0123456789') {
		if (!is_int($length) || $length < 0) {
			return false;
		}
		$charslength = strlen($chars) - 1;
		$str = '';
		for($i = $length; $i > 0; $i--) {
			$str .= $chars[mt_rand(0, $charslength)];
		}
		return $str;
	}
	$string = randomstring();
	print $string;
?>

Reversing the Words in a String

explode() a string, reverse the array created, and implode() to rejoin.

<?php
	$string = 'How now brown cow';
	$words = explode(' ', $string);
	$words = array_reverse($words);
	$string = implode(' ', $words);
	print $string;
?>

Or simply:

<?php
	$string = 'How now brown cow';
	$string = implode(' ', array_reverse(explode(' ', $string)));
	print $string;
?>

Wrapping Text

Use the wordwrap function to, without cutting words, wrap lines in a string for displaying between <pre> and </pre> tags. The first argument is the string to wrap, the second argument is the number of characters not to exceed per line, the third argument is the string to for line breaks, and the fourth argument tells the function what to do when the word exceeds the number of characters per line (1 to wrap these words, 0 to let them span past the specified line length).

<?php
	$string = 'how now brown cow how now brown cow how now brown cow how now brown cow how now brown cow how now brown cow how now brown cow';
	$string = wordwrap($string, 35, '\n', 0);
	print $string;
?>

Output CSV Files

Format data as comma-seperated values so that they can be imported by spreadsheet programs like Microsoft Excel.

Use the fputcsv function to create a CSV formatted line from an array. Use the header function to tell the browser to open a spreadsheet application for this output. Write to the output stream php://output.

<?php
$arr = array(
	array('172-32-1176','White','Johnson','408 496-7223'),
	array('213-46-8915','Green','Marjorie','415 986-7020'),
	array('238-95-7766','Carson','Cheryl','415 548-7723'),
	array('267-41-2394','O\'Leary','Michael','408 286-2428'),
	array('274-80-9391','Straight','Dean','415 834-2919'),
	array('341-22-1782','Smith','Meander','913 843-0462'),
	array('409-56-7008','Bennet','Abraham','415 658-9932'),
	array('427-17-2319','Dull','Ann','415 836-7128'),
	array('472-27-2349','Gringlesby','Burt','707 938-6445'),				
	array('486-29-1786','Locksley','Charlene','415 585-4620'),
	array('527-72-3246','Greene','Morningstar','615 297-2723'),
	array('648-92-1872','Blotchet-Halls','Reginald','503 745-6402'),
	array('672-71-3249','Yokomoto','Akiko','415 935-4228'),
	array('712-45-1867','del Castillo','Innes','615 996-8275'),
	array('722-51-5454','DeFrance','Michel','219 547-9982'),
	array('724-08-9931','Stringer','Dirk','415 843-2991'),
	array('724-80-9391','MacFeather','Stearns','415 354-7128'),
	array('756-30-7391','Karsen','Livia','415 534-9219'),
	array('807-91-6654','Panteley','Sylvia','301 946-8853'),
	array('846-92-7186','Hunter','Sheryl','415 836-7128'),
	array('893-72-1158','McBadden','Heather','707 448-4982'),
	array('899-46-2035','Ringer','Anne','801 826-0752'),
	array('998-72-3567','Ringer','Albert','801 826-0752')
);
$f = fopen('php://output', 'w') or die('Cannot open php://output');
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="authors.csv"');
foreach($arr as $arr_line) {
	if(fputcsv($f, $arr_line) === false) {
		die('Cannot write line');
	}
}
fclose($f) or die('Cannot close php://output');
?>

Dates and Times

Validate a Date

Use checkdate to check if a date is valid. The first parameter is the month, second is the day, and third is the year.

<?php
	if(!checkdate(2, 31, 2014)) {
		// Feb 31 2014 is not a valid date
	}
?>

Convert a String to a Date/Time

Use strtotime.

<?php
	$dt = strtotime('now');
	print date(DATE_RFC850, $dt).'<br />';

	$dt = strtotime('today');
	print date(DATE_RFC850, $dt).'<br />';

	$dt = strtotime('2/8/2014');
	print date(DATE_RFC850, $dt).'<br />';

	$dt = strtotime('2/8/2014 10:15');
	print date(DATE_RFC850, $dt).'<br />';
?>
<<<[Page 1 of 6]>>>

PROWAREtech

Hello there! How can I help you today?
Ask any question

PROWAREtech

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
ACCEPT REJECT