PHP String Exercises: Replace the first word with another word
Write a PHP script to replace the first 'the' of the following string with 'That'.
Sample date: 'the quick brown fox jumps over the lazy dog.'
Visual Presentation:
Sample Solution:
PHP Code:
<?php
// Define a string variable containing the phrase "the quick brown fox jumps over the lazy dog."
$str = 'the quick brown fox jumps over the lazy dog.';
// Use preg_replace function to replace the first occurrence of the word 'the' with 'That' in the string.
// The pattern '/the/' is a regular expression pattern matching the word 'the'.
// 'That' is the replacement string.
// The '1' parameter specifies that only the first occurrence of 'the' should be replaced.
echo preg_replace('/the/', 'That', $str, 1)."\n";
?>
Output:
That quick brown fox jumps over the lazy dog.
Explanation:
In the exercise above,
- <?php: This tag indicates the beginning of PHP code.
- $str = 'the quick brown fox jumps over the lazy dog.';: This line initializes a string variable $str with the value 'the quick brown fox jumps over the lazy dog.'.
- echo preg_replace('/the/', 'That', $str, 1)."\n";:
- preg_replace() is a PHP function used for performing a regular expression search and replace.
- /the/ is a regular expression pattern that matches the word 'the' in the string.
- 'That' is the replacement string that replaces the matched word.
- $str is the input string on which the replacement operation is performed.
- 1 is the fourth parameter, which specifies the maximum number of replacements to be made. In this case, it's set to 1, meaning only the first occurrence of 'the' will be replaced.
- echo is used to output the replacement result.
- ."\n" adds a newline character at the end of the output for better formatting.
Flowchart:
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a PHP script to generate simple random password [do not use rand() function] from a given string.
Next: Write a PHP script to find the first character that is different between two strings.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics