PHP Working With Strings

PHP Code Snippets Working With Strings


In this code snippet, we’ll learn how to work with strings in PHP.

More specifically we’ll learn how to concatenate(join) strings, trim white spaces, make a string lower or upper case, get its length, check if it contains a substring and get its position, replace a substring, remove tags and slashes, split a string into an array on a specific character and join a string array back into a string.

Note: I covered just the string functions I found myself using the most. Here is the full list of string functions.

Let’s see the example code below.



//Concatenate strings with the . operator.
$myString = "Hello" . "" . "World! ";

//Trims whitespace.
echo "String length: " . trim($myString);
echo "<br>";

//Makes string lowercase.
echo "String to lower case: " . strtolower($myString);
echo "<br>";

//Makes string uppercase.
echo "String to upper case: " . strtoupper($myString);
echo "<br>";

//Get string length.
echo "String length: " . strlen($myString);
echo "<br>";

//Checks if a string contains a substring.
echo "Contains 'World': " . str_contains($myString, "World");
echo "<br>";

//Gets position of the first substring.
echo "Position of 'World': " . stripos($myString, "World");
echo "<br>";

//Replace substring.
echo "Replace 'Hello': " . str_replace("Hello", "Goodbye", $myString);
echo "<br>";

//Removes slashes from string.
echo "Strip slashes: " . stripslashes("File\Name.txt");
echo "<br>";

//Removes tags from string.
echo "Remove tags: " . strip_tags("<h1>Hello World!</h1>");
echo "<br>";

//Split string into an array of strigs on a certain character.
$charArray = explode(" ", $myString);
echo "Explode: ";
    echo "<pre>";
    echo "</pre>";
echo "<br>";

//Makes string from a string array.
echo "Implode: " . implode($charArray);

Resulting Output:


Leave a Reply

Your email address will not be published.

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger