PHP Basic String Manipulation Techniques

Lesson Overview

Welcome! In this lesson, we'll delve into the basic string manipulation features of PHP, which include string tokenization, string concatenation, trimming whitespace from strings, and type conversion operations.

Tokenizing a String in PHP

In PHP, we can use the explode function to tokenize a string, essentially splitting it into smaller parts or 'tokens'.

Using explode function:

PHP
<?php
$sentence = "PHP is a versatile language!";
$tokens = explode(" ", $sentence);

foreach ($tokens as $token) {
    echo $token . "\n";
}
?>

In the example above, we use a space as a delimiter to split the $sentence into words. This operation will print each word in the sentence on a new line.

Exploring String Concatenation

In PHP, the . operator or implode function can be used to concatenate strings into a larger string:

Using the . Operator:

PHP
<?php
$str1 = "Hello,";
$str2 = " World!";
$greeting = $str1 . $str2;
echo $greeting;  // Output: "Hello, World!"
?>

Using implode:

PHP
<?php
$strings = array("Hello", " World!", " PHP", " functions!");
$result = implode("", $strings);
echo $result;  // Output: "Hello World! PHP functions!"
?>

In the example above, implode is used to concatenate all the elements of an array into a single string.

Trimming Whitespaces from Strings

In PHP, the trim function can remove both leading and trailing whitespaces from a string:

PHP
<?php
$str = "    Hello, World!    "; // string with leading and trailing spaces
$str = trim($str); // remove leading and trailing spaces
echo $str; // Output: "Hello, World!"
?>

In this example, trim is used to remove leading and trailing whitespaces from a string.

PHP Type Conversions

We can convert strings to numbers using functions like intval (string to integer) and floatval (string to float), and other data types to strings using simple concatenation or casting:

PHP
<?php
$numStr = "123";
$num = intval($numStr);
echo $num . "\n";  // Output: 123

$floatStr = "3.14";
$pi = floatval($floatStr);
echo $pi . "\n";  // Output: 3.14

$age = 20;
$ageStr = (string)$age;
echo "I am " . $ageStr . " years old."; // Output: I am 20 years old.
?>

In this code, we use intval, floatval, and simple casting for type conversions.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal