w3resource

PHP String Exercises: Replace the first word with another word


10. Replace First Occurrence of "the"

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:

PHP String Exercises: Replace the first word with another word

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:

Flowchart: Replace the first word with another word

For more Practice: Solve these Related Problems:

  • Write a PHP script to replace only the first occurrence of the substring "the" with "That" in a sentence, ensuring case sensitivity.
  • Write a PHP function that searches for the first instance of a given word in a string and replaces it with a new word.
  • Write a PHP program to replace the first occurrence of a substring, then output both the modified and original strings for comparison.
  • Write a PHP script to use a regular expression with a limit to replace just the first instance of "the" in a text block.

Go to:


PREV : Generate Random Password Without rand().
NEXT : Find First Character Difference Between Strings.

PHP Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.