Search code examples
phplaravelexplode

How to get word after user input in textarea?


I have a text area to user to insert text, but if the user type {{name}}, {{nickname}} and {{email}}. It must show the message with that value. Let me demonstrate: For example: If user type: Hello, {{name}} has {{nickname}} and {{email}} the message must be like this: Hello, user A has nickname A and [email protected].

This is my blade view:

// User insert text here
<textarea name="content" value=""></textarea>

My controller:

// My controller did not work, but I want to know how to use explode
$content = $request->input('content');
$new_content = explode($content, '{{name}}', '{{nickname}}', '{{email}}');

Solution

  • This is an approach I've used in a number of projects to allow template input and functions that return replacements.

    here, $subject is the text being modified.

        preg_match_all('/{{(\S*)}}/',$subject,$matches,PREG_SET_ORDER);
        
        foreach($matches as $match) {
            $func = 'replace_'.$match[1];
            if(method_exists($this,$func)) {
                $subject = str_replace($match[0], $this->$func($match), $this->subject);
            }
        }
    
    

    You can then create functions that start with replace_ and return the string to be inserted in the original message

    eg

    public function replace_name($match)
    {
      return $$this->user->name;
    }