PHP Strings

Common string functions.

✍️ 2 exercises in this lesson

PHP has hundreds of string functions. The most useful:

  • strlen(): length
  • str_word_count(): number of words
  • strtoupper(), strtolower(), ucfirst(), ucwords()
  • str_replace(search, replace, subject)
  • strpos() and str_contains(): search
  • substr(): part of a string
  • trim(), explode(), implode(), sprintf()

Key Takeaways: PHP Strings

Mastering PHP Strings helps you write clean and reliable PHP code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

PHP Strings Code Example

PHP
<?php
$text = "  learn php at codesintech  ";
$clean = trim($text);

echo strlen($clean) . "<br>";
echo ucwords($clean) . "<br>";
echo str_replace("php", "Laravel", $clean) . "<br>";
echo substr($clean, 6, 3) . "<br>";
var_dump(str_contains($clean, "codes"));
echo "<br>" . implode(" | ", explode(" ", $clean));
echo "<br>" . sprintf("%05.1f%%", 7.5);
Output
24
Learn Php At Codesintech
learn Laravel at codesintech
php
bool(true)
learn | php | at | codesintech
007.5%
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

PHP Strings Practice Exercises

Check what you learned in “PHP Strings”.

/ 2 solved
Fill in the blank

Get the length of a string.

echo ("Hello");
✓ Correct! Not quite. Try again.
Multiple choice

Which function replaces text inside a string?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services