Real World PHP

About   |   EN   |   ES

007 More Strings

We've already gone over the basics of strings the 006d Data Types: Strings chapter. However, there is a lot more that can be done with string handling and manipulation.

PHP has a lot of functions related to strings. We will review a handful of those functions here to get an idea of what is available. These are not necessarily the best functions or the most used functions. These are just a handful to get an idea of what is available and how they work.

echo()

The echo() function will output a string to the screen. We've already introduced this method in the 003 Hello World chapter.

explode() and implode()

The explode() function will split a string by a string into an array. And implode() takes an array and turns it into a string. These can be convenient functions as a lot of data comes as a long string divided up by convenient sub-strings.

<?php
// explode(separator, string_to_explode, optional_limit)
$exploded = explode(" ", "This is a string.");

print_r($exploded);
// Output:
// Array
// (
//     [0] => This
//     [1] => is
//     [2] => a
//     [3] => string.
// )

// implode(separator, array)
$imploded = implode(" ", $exploded);
echo $imploded;
// Output:
// This is a string.

htmlspecialchars()

The htmlspecialchars() function will convert special characters into html entities. This is helpful when you need to sanitize user input. It can play an important part of securing your code. You will need to do much more to be secure, but it may play a part of your approach to security.

<?php
// htmlspecialchars(string, optional_flags, optional_encoding, optional_double_encoding)
$ouput = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $output; // &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;

ord() and chr()

The ord() function will convert the first byte of a string to a value between 0 and 255. The chr() function will do the inverse. These functions can be useful when you have a situation where you need to have a character be a numeric value.

<?php
// ord(character)
$char = ord("A");
echo $char; // 65

// chr(numeric_code)
$num = chr($char);
echo $num; // "A"

sprintf()

The sprintf() function will return a formatted string. This is a very flexible function that has its roots in sprintf() from the programming language C. It allows you to format a string in many different ways. Be sure to review the documentation for the many different formatting options available.

<?php
// sprintf(string_format, value1, value2, ...)
echo sprintf('There are %d monkeys in the %s', 5, 'tree');
// Output:
// There are 5 monkeys in the tree

str_contains() and substr()

The str_contains() function determines if a string contains a given substring. The substr() function will return a portion of a string. str_contains() is helpful if you just need to know that the substring is there. substr() is useful for getting a portion of a string when you know where in the string it is located. Note that the position offset starts at 0 from the left. If you give it a negative number, it will begin from the right.

<?php
// str_contains(haystack, needle)
var_dump(str_contains("Surreal", "real"));
// output: true

// substr(string, offset, optional_length)
$output = substr("Hello, world!", 7, 5);
echo $output; // "world"

str_replace()

str_replace() will replace all occurrences of the search string with the replacement string. Note that str_replace() doesn't change the subject you pass in. It just gives you a new string with the replacement.

<?php
// str_replace(search, replace, subject, optional_count)
$subject = "Java is the best!";
$output = str_replace("Java", "PHP", $subject);
echo $output; // "PHP is the best!"

str_split()

The str_split() function converts a string into an array, where each character is an item in the array, unless specified otherwise.

<?php
// str_split(string, optional_length)
$string = "Hello!";
$result1 = str_split($string);
print_r($result1);
// Output:
// Array
// (
//     [0] => H
//     [1] => e
//     [2] => l
//     [3] => l
//     [4] => o
//     [5] => !
// )

$result2 = str_split($string, 3);
print_r($result2);
// Array
// (
//     [0] => Hel
//     [1] => lo!
// )

strlen()

The strlen() function will count the number of characters in a string.

<?php
// strlen(string)
echo strlen("Hello"); // output: 5

strpos() and stripos()

Both the strpos() and stripos() functions find the position of the first occurrence of a substring in a string. The difference is that stripos() is case insensitive.

<?php
// strpos(haystack, needle, optional_offset)
echo strpos("Hello", "l"); // 2
echo strpos("Hello", "L"); // false

// stripos(haystack, needle, optional_offset)
echo stripos("Hello", "l"); // 2
echo stripos("Hello", "L"); // 2

strtolower() and strtoupper() and ucfirst() and ucwords()

Sometimes you need a letter or letters to change from uppercase to lowercase or vice versa. strtolower() changes all the letters in a string to lowercase. strtoupper() changes all the letters in a string to uppercase. ucfirst() will change the first letter in a string to uppercase. ucwords() will change the first character of each word in a string to uppercase.

<?php
// strtolower(string)
echo strtolower("Hi! How Are YOU?");
// "hi! how are you?"

// strtoupper(string)
echo strtoupper("Hi! How are YOU?");
// "HI! HOW ARE YOU?"

// ucfirst(string)
echo ucfirst("i love PHP!");
// "I love PHP!"

// ucwords(string, optional_separators)
echo ucwords("i love php!");
// "I Love Php!"

trim()

The trim() function will remove whitespace from the start and end of a string.

<?php
// trim(string, optional_characters)
echo trim("  Real World PHP  ");
// "Real World PHP"


Resources


Challenges

Comma Separated Values

Take the string "Up,Up,Down,Down,Left,Right,Left,Right":

  1. Convert it into an array where each word is a value in the array (the commas will not be part of the array)
  2. Convert the array back into a string, but each item is separated by a space instead of a comma.
  3. Make the string all lowercase.
  4. Replace each space with the hyphen character "-"

Your final output should be:
"up-up-down-down-left-right-left-right"