Viewed   73 times

I have string like this in database (the actual string contains 100s of word and 10s of variable):

I am a {$club} fan

I echo this string like this:

$club = "Barcelona";
echo $data_base[0]['body'];

My output is I am a {$club} fan. I want I am a Barcelona fan. How can I do this?

 Answers

4

Use strtr. It will translate parts of a string.

$club = "Barcelona";
echo strtr($data_base[0]['body'], array('{$club}' => $club));

For multiple values (demo):

$data_base[0]['body'] = 'I am a {$club} fan.'; // Tests

$vars = array(
  '{$club}'       => 'Barcelona',
  '{$tag}'        => 'sometext',
  '{$anothertag}' => 'someothertext'
);

echo strtr($data_base[0]['body'], $vars);

Program Output:

I am a Barcelona fan.
Tuesday, September 6, 2022
4

You need a Ajax call to pass the JS value into php variable

JS Code will be (your js file)

var jsString="hello";
$.ajax({
    url: "ajax.php",
    type: "post",
    data: jsString
});

And in ajax.php (your php file) code will be

$phpString = $_POST['data'];     // assign hello to phpString 
Thursday, November 10, 2022
 
2

alert('my name is: <?php echo $man; ?>' );

Friday, August 19, 2022
 
2

Note that your calls are structured in such a way that W is replaced with Y in the first call, and then Y is again replaced with W in the third call, undoing the first call's output.

You should be using str.translate, it's much more efficient and robust than a bunch of chained replace calls:

_tab = str.maketrans(dict(zip('WXYZ', 'YZWX')))
def replace(string):
    return string.translate(_tab)

>>> replace('WXYZ')
'YZWX'
>>> replace("WWZYWXXWYYZW")
'YYXWYZZYWWXY'
Friday, September 2, 2022
1

Check out this post: JavaScript equivalent to printf/string.format

Tuesday, August 9, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :