Skip to content

Get the first letter of each word in a string โ€‹

You can use the preg_match_all function in PHP to match all the words in a string and then use the substr function to get the first letter of each word. Here is an example:

Example of getting the first letter of each word in a string in PHP

php
<โ€Œ?php

$string = "This is a test string";
preg_match_all('/\b\w/', $string, $matches);
echo $firstLetters = implode('', $matches[0]);

<div class="alert alert-info flex not-prose"> Watch a course Learn object oriented PHP</div>

The preg_match_all function searches for all occurrences of the regular expression /\b\w/ in the string, which matches the first letter of each word. The implode function is used to join the array of first letters into a single string.

Dual-run preview โ€” compare with live Symfony routes.