The Top 9 Most Popular PHP String Functions

The Top 9 Most Popular PHP String Functions

Strings are everywhere in our lives and in our programming. When we think of reading text, what we’re really doing is reading strings in a sense. In PHP a string is just an array of characters. There are several ways to define strings, and many ways to use the built in PHP functions to operate on them. Let’s take a look at the various ways we can define strings, and then we’ll cover The Top 9 Most Popular PHP String Functions, similar to our popular most used array functions in PHP blog post. Let’s jump in!


Defining Strings in PHP

There are three main ways to define strings in PHP. We have:

  • Characters enclosed in double quotes.
  • Characters enclosed in single quotes.
  • Characters or lines of characters enclosed by heredoc symbols

Double Quotes
Double quotes are useful when you have a PHP variable you want to embed within the string, since when the PHP runs, it will use interpolation to grab the actual value of that variable.


$str = "Hi buddy, I'm a PHP String";

Single Quotes
Some people find it easier to leave their variables out of strings and let them be more hard coded sort to speak. Use single quotes for that.


$str = 'Hi again, still a PHP String!';

Heredoc Syntax


$str = <<<EOD
Wordpress is really cool
HTML5 is the key to the open web
Who likes to use Twitter Bootstrap
We can have several lines here!
EOD;

Note: You don’t have to use EOD as your delimiter, you can use anything you like as long as they are the same!


Most Popular PHP String Functions

1. substr()

The substr() function helps you to access a substring between given start and end points of a string. It can be useful when you need to get at parts of fixed format strings.

The substr() function prototype is as follows:


string substr(string string, int start[, int length] );

The return value is a substring copied from within string.


$blog = 'Your Blog is Excellent!';

When you call the function with a positive number for start (only), you will get the string from the start position to the end of the string.


$blog = 'Your Blog is Excellent!';
substr($blog, 1);
//  returns 'our Blog is Excellent!'

String position starts from 0, just like arrays.

When you call substr() with a negative start (only), you will get the string from the end of the string minus start characters to the end of the string.


$blog = 'Your Blog is Excellent!';
substr($blog, -9);
//  returns 'xcellent!'

The length parameter can be used to specify either a number of characters to return if it is positive, or the end character of the return sequence if it is negative.


$blog = 'Your Blog is Excellent!';
substr($blog, 0, 4);
// returns 'Your'

substr($blog, 5, -13);
//returns 'Blog'

5 signifies the starting character point (B) and -13 determines the ending point (count 13 places backwards starting from the end of the string).

Learn more about substr() at http://us3.php.net/substr


2. strlen()

Next up we have the popular strlen() function for checking the length of a string. If you pass it a string, strlen() will return its length.


echo strlen("Super Cali Fragilistics Expy Ali Docious");
// 40

Often times this function is used for validating input data or making sure a string variable has a value.


<?php
$super = 'duper';

if (strlen ( $super ) > 0) {
	echo 'Thanks for giving super some duper';
} else {
	echo 'That might not have worked';
}
?>
// Thanks for giving super some duper

Learn more about strlen() at http://us3.php.net/strlen


3. str_replace()

Find and replace functionality is super useful with strings. You can use find and replace for almost anything your imagination can think of.

The most commonly used string function for replacement is str_replace(). It has the following prototype:


mixed str_replace(mixed needle, mixed new_needle, mixed haystack[, int &count]));

str_replace() replaces all the instances of needle in haystack with new_needle and returns the new version of the haystack.The optional fourth parameter contains the number of replacements made.

A really awesome feature of str_replace() is the ability to pass an array to both the search terms and replace terms, as well as an array of strings to apply the rules to!


<?php
$strings = array (
		'You like to have a fun time',
		'You are a really nice person',
		'Would you like to have a cup of coffee?' 
);

$search = array (
		'fun',
		'time',
		'person',
		'coffee' 
);
$replace = array (
		'excellent',
		'adventure',
		'individual',
		'joe' 
);

$replaced = str_replace ( $search, $replace, $strings );

print_r ( $replaced );

/////////////////////////////////
Array
(
    [0] => You like to have a excellent adventure
    [1] => You are a really nice individual
    [2] => Would you like to have a cup of joe?
)
?>

Learn more about str_replace() at http://php.net/manual/en/function.str-replace.php


4. trim()

The first step in tidying up data is to trim any excess whitespace from the string. This is a good idea to prepare for a database insert or string comparison.

The trim() function strips whitespace from the start and end of a string and returns the resulting string. The characters it strips by default are newlines and carriage returns (n and r), horizontal and vertical tabs (t and x0B), end-of-string characters (), and spaces. You can also pass it a second parameter containing a list of characters to strip instead of this default list. Depending on your particular purpose, you might like to use the ltrim() or rtrim() functions instead which perform the same operation, but you choose which side of the string to affect.

Here we remove some literal junk from the beginning and end of our string:


<?php
$trimit = 'junk awesome stuff junk';

$trimmed = trim ( $trimit, 'junk' );

print_r ( $trimmed );

// awesome stuff 
?>

Learn more about trim() at http://us2.php.net/manual/en/function.trim.php


5. strpos()

The function strpos() operates in a similar fashion to strstr(), except, instead of returning a substring, it returns the numerical position of a needle within a haystack.

The strpos() function has the following prototype:


int strpos(string haystack, string needle, int [offset] );

The integer returned is the position of the first occurrence of the needle within the haystack. The first character is in position 0 just like arrays.

We can see by running the following code that our exclamation point is at position 13.


$awesome = "Super Awesome!";
echo strpos($awesome, "!");
// 13

This function accepts a single character as the needle, but it can accept a string of any length. The optional offset parameter determines the point within the haystack to start searching.


$awesome = "Super Awesome!";
echo strpos($awesome, ‘m’, 3);
// 11

This code echoes the value 11 to the browser because PHP has started looking for the character ‘m’ at position 3.

In any of these cases, if the needle is not in the string, strpos() will return false. To avoid strange behavior you can use the === operator to test return values:


<?php
$awesome = "Super Awesome!";

$result = strpos ( $awesome, G );
if ($result === false) {
	echo 'Not found';
} else {
	echo 'Found at position ' . $result;
}

// Not found
?>

Learn more about strpos() at http://us2.php.net/strpos


6. strtolower()

Very often in PHP we need to compare strings or correct capitalization when people SHOUT or do odd things. In order to compare strings, you want to make sure they are the same case. We can use strtolower() for this purpose. We’ll use a function created with strtolower() to calm down an angry person.


<?php
function calm_down($string) {
	
	return strtolower ( $string );
}

$person = 'Angry people SHOUT!';

echo calm_down ( $person );
// angry people shout!
?>

Learn more about strtolower() at http://us3.php.net/strtolower


7. strtoupper()

strtoupper() is also quite popular for many of the reasons listed above, in reverse, meaning take lowercase or a mixed case string and set it to all upper case. We’ll change things up and create a wake up function to get our workers going in the morning.


<?php
function wake_up($string) {
	
	return strtoupper ( $string );
}

$person = 'these people need to get working!';

echo wake_up ( $person );
// THESE PEOPLE NEED TO GET WORKING!
?>

Learn more about strtoupper() at http://us3.php.net/strtoupper


8. is_string()

is_string() is used to check if a value is a string. Let’s take a look at this within an if() statement to take an action on strings in one way and non-strings in another. is_string() returns true or false.


<?php
if (is_string ( 7 )) {
	echo "Yes";
} else {
	echo "No";
}
// No

if (is_string ( "Lucky Number 7" )) {
	echo "Yes";
} else {
	echo "No";
}
// Yes
?>

Learn more about is_string() at http://us2.php.net/is_string


9. strstr()

Last but not least we have the strstr() function. The function strstr() can be used to find a string or character match within a longer string. This function can be used to find a string inside a string, including finding a string containing only a single character.

The function prototype for strstr() is as follows:


string strstr(string haystack, string needle);

You pass strstr() a haystack to be searched and a needle to be found. If an exact match of the needle is found, the strstr() function returns the haystack from the needle onward. If it does not find the needle, it will return false. If the needle occurs more than once, the returned string will begin from the first occurrence of the needle.

As an example, let’s say we have a submission form for people to submit their website, but we would like it in a certain format. We can use strstr() to check for a string within a string to help us here:


<?php
$url = 'vegibit.com';

if (strstr ( $url, 'https://www.' ) === false) {
	$url = 'http://www.' . $url;
}

echo $url;
// https://www.vegibit.com
?>

Learn more about strstr() at http://us2.php.net/strstr

By getting a mastery of these very commonly used string functions, you’ll be well on your way to getting all kinds of tasks completed in your applications. If you enjoyed this tutorial, you may also enjoy our JavaScript String Functions tutorial as well!