Search code examples
phpstringsubstring

Replace string between two char(special symbol) in php


I have a string like: He *is* a good boy. How *are* you. Then I want to replace is and are with input type textbox means replace things between asterisk(*). How can I get this Please help me out.


Solution

  • <?php
        $buffer = 'He *is* a good boy. How *are* you.';
        echo "Before: $buffer<br />";
        $buffer = preg_replace_callback('/(\*(.*?)\*)/s', 'compute_replacement', $buffer);
        echo "After: $buffer<br />";
    
        function compute_replacement($groups) {
            // $groups[1]: *item*
            // $groups[2]: item
            return '<input type="text" value="'.$groups[2].'" />';
        }
    ?>
    

    The result:

    enter image description here