How to replace a word inside a string in PHP?

How to replace a word inside a string in PHP?

Asked on November 1, 2018 in PHP.
Add Comment


  • 1 Answer(s)

    Here PHP str_replace() function is used.
    The PHP str_replace() function is used to replace all the occurrences of a word within a string.

    In the below example the word “facts” is replaced by the word “truth”.

    For example:

    <?php
    $my_str = 'If the facts do not fit the theory, change the facts.';
     
    // Display replaced string
    echo str_replace("facts", "truth", $my_str);
    ?>
    

    PHP str_replace() function is case-sensitive, if want to perform case-insensitive match and replace then use str_ireplace() function.

    Answered on November 1, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.