Home »
PHP »
PHP Programs
Write a PHP script, which changes the color of the first character of a word
By Shahnail Khan Last updated : December 19, 2023
Problem statement
Write a PHP script, which changes the color of the first character of a word.
Sample string: Hello! Welcome to Includehelp.
Expected Output:
Hello! Welcome to Includehelp.
Prerequisites
To understand this solution better, you should have the basic knowledge of the following PHP topics:
Changing the color of the first character of a word in PHP
To change the color of the first character of a word in a string using PHP script, we use the preg_replace() function.
In PHP, the preg_replace() function is used for performing regular expression-based search and replacing a string. It allows you to search for a pattern in a given string and replace it with another specified value.
Syntax of preg_replace():
preg_replace( $pattern, $replacement, $subject, $limit, $count )
- $pattern: This is the regular expression pattern you want to search for in the $subject string.
- $replacement: The value that will replace the matched pattern in the $subject string.
- $subject: The original string where the search and replace will occur.
- $limit: (Optional) The maximum number of replacements to perform. Use -1 for no limit.
- $count: (Optional) If provided, this variable will be filled with the number of replacements done.
PHP script to change the color of the first character of a word
The code given below is used for changing the color of the first character of a word in PHP.
<!DOCTYPE html>
<html>
<head>
<title>Change Color of First Character</title>
</head>
<body>
<?php
function changeColor($inputString, $color)
{
// Use a regular expression to match the first character of each word
$pattern = "/\b(\w)/u";
$replacement = "<span style='color: $color;'>$1</span>";
$modifiedString = preg_replace($pattern, $replacement, $inputString);
return $modifiedString;
}
$inputString = "Hello! Welcome to Includehelp.";
$modifiedString = changeColor($inputString, "blue");
echo "<p>$modifiedString</p>";
?>
</body>
</html>
Output
The output of the given code is:
Code Explanation
- The changeColor() function takes two parameters: $inputString (the original string) and $color (the color to be applied).
- Inside the function, a regular expression pattern (/\b(\w)/u) is used to match the first character of each word.
- $replacement is a string containing an HTML <span> element with an inline style to set the color. $1 in the replacement refers to the matched character.
- preg_replace is then used to replace the matched characters with the specified HTML code, resulting in a modified string.
- $inputString is defined: "Hello! Welcome to Includehelp."
- The changeColor function is called with this string and a specified color ('blue').
- Then the original string with the first character of each word is now colored in blue.
More PHP Programs »