Thursday, September 4, 2025
HomeLanguagesHow to change the color of the first character of a word...

How to change the color of the first character of a word using PHP script?

The preg_replace() function is an in-built function that returns a word or array of words with the replacement of some content after searching the pattern. If the search pattern is not found then it will be returned unchanged. 

Approach:

  • Declare a variable with a string value.
  • Use preg_replace() function to replace the first character of every word.
  • Display the replaced value of the string variable. 

Example 1:

PHP




<?php
  
// Text to replace
$text = "Geeks For Geeks";
  
// The preg_replace is used here to replace the 
// color of first character of the word
$text = preg_replace('/(\b[a-z])/i'
'<span style="color:green;">\1</span>', $text);
  
// Display the text value
echo $text
?>


Output:

Example 2:

PHP




<?php
  
// Text to replace
$text = "Practice code in GEEKSFORGEEKS";
  
// The preg_replace is used here to replace the 
// color of first character of the word
$text = preg_replace('/(\b[a-z])/i'
'<span style="color:green;">\1</span>', $text);
  
// Display the text value
echo $text
?>


Output:

RELATED ARTICLES

Most Popular

Dominic
32263 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11799 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11857 POSTS0 COMMENTS
Shaida Kate Naidoo
6749 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6696 POSTS0 COMMENTS
Umr Jansen
6716 POSTS0 COMMENTS