Tuzz Samuel
Tuzz Samuel

Reputation: 55

How to parse html textarea input for special variable

I want users to represent a special variable say someone's name by something like the string {name} in their text area submission, how do I now parse that textarea input with PHP or JS to convert {name} back to an actual name and not use {name} literally?

Upvotes: 1

Views: 356

Answers (2)

Omari Victor Omosa
Omari Victor Omosa

Reputation: 2879

You can use str_replace to replace all occurrence of {name}. i.e.

<?php

$string = "someone's name by something like the string {name} in their text area submission, how do I now parse that textarea input with PHP or JS to convert {name} back to an actual name and not use {name} literally?";

$replaced = str_replace('{name}', 'MR.real name', $string);

echo  $replaced;

?>

Upvotes: 0

onecompileman
onecompileman

Reputation: 940

Something like this? I have created a function putContent where in you put the the value you want to replace if there's many {name}, {last_name} that you want to replace with

const textareaStr = '{first_name} is my name, and ${last_name} is my last name';

const firstName = 'Naruto';
const lastName = 'Uzumaki';

let newStr = textareaStr;

newStr = putContent(newStr, 'first_name', firstName);
newStr = putContent(newStr, 'last_name', firstName);
console.log(newStr);



function putContent(str,key, value) {
   return str.replace(new RegExp(`{${key}}`, 'g'), value);
}

Upvotes: 1

Related Questions