wiki:Php Strings

php Strings

Declare a String

Here are the basic ways to declare/use strings in php:


	$str = "here is a string.";
	$str2 = 'Here is another string.';


Double or single quotes can be used, but there are differences. There will be times when it is better to use one over the other, but for the most part it is just a matter of convention.

Single Quotes

These should be used when your string data contains a lot of double quotes, like for HTML code


	//single quoted
	$str = '<img src= "/image.jpg" alt= "HUrr-duRRr" />';

	//double quoted equivalent (must use escape char)
	$str2 = "<img src= \"/image.jpg\" alt= \"HUrr-duRRr\" />";


In associative array keys, you could use either, but as a convention, it is best to stick to one type

	echo $assoc_arr['key'];

more on arrays later.

Double Quotes

It makes for cleaner code to use double quotes if you are using a lot of variables in your strings. If you need to use escape sequences like newline, tab, use double quotes.


	$a_var1 = 3;
	$a_var2 = 'some text';

	$str = "here is {$a_var2}, and php treats {$a_var1} as a string in this case.";

	//Single quotes would force you to use concat operators here
	$str2 = 'here is '. $a_var2 .', and php treats '. $a_var1 .' as a string in this case.';


Enclosing the variables in braces is not required here, but makes for cleaner code.

Outputting Strings

There are a number of ways to output strings, since this is what php was designed to do

	echo "Hello";
	print "Hello"; //the logic behind it is slightly different, but gives the same result.



This is another way to output, it could be used if you have a chunk of straight HTML that you don't want to make php variables or mess with the quotes/formatting in an echo stmt. Remember that we're outputting HTML that is viewed in a browser, so carriage returns/tabs/newlines won't be seen in the browser, but will be seen in the html source. This way will output the source exactly as given:



<h1>Hello World</h1>

	$str = <<<DEMO
     This is a
        demo message
              with heredoc.

	echo $str;


Whatever appears after the <<< is treated like a variable, and anything between the <<<DEMO and DEMO is the output text. You must place the ending DEMO on its own line and must be the first thing that appears on the line.

The complete and very useful string reference can be found at:

Some php string functions of interest

array explode ( string $delimiter , string $string [, int $limit ] )

Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter.

	// Example 1
	$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
	$pieces = explode(" ", $pizza);
	echo $pieces[0]; // piece1
	echo $pieces[1]; // piece2

	// Example 2
	$data = "foo:*:1023:1000::/home/foo:/bin/sh";
	list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
	echo $user; // foo
	echo $pass; // *


array str_split ( string $string [, int $split_length = 1 ] )

Converts a string to an array.


	$str = "Hello Friend";

	$arr1 = str_split($str);
	$arr2 = str_split($str, 3);




    [0] => H
    [1] => e
    [2] => l
    [3] => l
    [4] => o
    [5] =>
    [6] => F
    [7] => r
    [8] => i
    [9] => e
    [10] => n
    [11] => d

    [0] => Hel
    [1] => lo
    [2] => Fri
    [3] => end

mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

This function returns a string or an array with all occurrences of search in subject replaced with the given replace value.

If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of ereg_replace() or preg_replace().

If search and replace are arrays, then str_replace() takes a value from each array and uses them to search and replace on subject. If replace has fewer values than search, then an empty string is used for the rest of replacement values. If search is an array and replace is a string, then this replacement string is used for every value of search. The converse would not make sense, though.

If search or replace are arrays, their elements are processed first to last.

  • search - The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.
  • replace - The replacement value that replaces found search values. An array may be used to designate multiple replacements.
  • subject - The string or array being searched and replaced on, otherwise known as the haystack. If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well.
  • count - If passed, this will be set to the number of replacements performed.
	// Provides: <body text='black'>
	$bodytag = str_replace("%body%", "black", "<body text='%body%'>");

	// Provides: Hll Wrld f PHP
	$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
	$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");

	// Provides: You should eat pizza, beer, and ice cream every day
	$phrase  = "You should eat fruits, vegetables, and fiber every day.";
	$healthy = array("fruits", "vegetables", "fiber");
	$yummy   = array("pizza", "beer", "ice cream");

	$newphrase = str_replace($healthy, $yummy, $phrase);

	// Provides: 2
	$str = str_replace("ll", "", "good golly miss molly!", $count);
	echo $count;

The complete list of php string functions can be found at:

Last modified 9 years ago Last modified on Mar 17, 2011, 8:05:46 PM