Get DevWP - WordPress Development Theme

PHP Strings

Subscribe To PixemWeb on YouTube

A PHP String is a sequence of letters and words like a sentence or name, numbers that are a String Type, special characters or combination of all these characters.

You can create a string by nesting it in between a matching pair of single quotes ” or double quotes “”. You can also store a String in a Variable and echo it out.


<?php
  $stringexample = 'Hello World';
  echo $stringexample . '<br>';
  echo "Hello World Again";
?>

Working with PHP Strings

PHP has a lot of built in functions that help you work directly with Strings.

Return the Length of a String

You can use the PHP strlen() function to return the length of a string.


<?php
  $stringexample = 'Hello World';
  echo strlen($stringexample) . '<br>';
  echo strlen("Hello World Again");
?>

Uppercase the first letter of the first word

You could use ucfirst() function to accomplish this goal as demonstrated below.


<?php
  $firstname = 'joel is my first name.';
  echo ucfirst($firstname);
?>

Upper Case the first letter of all Words in a String

For this, you would use the PHP function ucwords() as demonstrated below.


<?php
  $fullname = 'joel rivera';
  echo ucwords($fullname);
?>

Lowercase all letters in a word

This is helpfull if a person fills out a form and accidently mixes up the case of various letters.


<?php
  $makelower = 'hELlo wOrlD';
  echo strtolower($makelower);
?>

You can combine PHP String Functions as well

This is where you can start taking full advantage of PHP. Below we have a variable called $fullname that has a name as a value that is mixed case. You can nest the strtolower() inside the ucwords() to fix the name and make it look right.
ucwords(strtolower($fullname))


<?php
  $fullname = 'jOEl rIVerA';
  echo ucwords(strtolower($fullname));
?>

Let’s break down what’s happening in the example above.

  • The variable $fullname is first being proccessed by strtolower($fullname) which makes every letter lowercased.
  • Then you see that strtolower($fullname) is completely nested inside the ucwords(strtolower($fullname)) which makes the first letter of each word uppercase.
  • Key thing to notice is the inner function is the first function to process the string and then the outer funciton is next.

Count the Words in a String

This is helpful if you want a word count.


<?php
  $howManyWords = 'How many words are in this string.';
  echo str_word_count($howManyWords);
?>

As you can see, PHP has numerous ways for you to work with Strings.



View Our Themes

Let's Connect