1

In PHP, I have string like this:

"Lorem ipsum dolor sit amet, {consectetur} adipiscing elit. Sed cursus ante dapibus {diam}.";

and I want to find and replace words inside {} with "BINGO".

Results:

"Lorem ipsum dolor sit amet, BINGO adipiscing elit. Sed cursus ante dapibus BINGO."

Any help would be greatly appreciated.

9
  • You want the same value for all between {}? why? Commented Apr 27, 2018 at 8:22
  • This is just example. Commented Apr 27, 2018 at 8:26
  • Is this for templating placeholders, or do you only want to change to one value? Anyways, my answer below covers both. Commented Apr 27, 2018 at 8:27
  • Actually i have equation inside {(123+2)/2}. I need calculate and print ansver. Commented Apr 27, 2018 at 8:31
  • lol, you left the biggest part out.. your need to regex that out, and eval it, then use the result as the value. You need to open a new question, you cant move the goal posts like that. Commented Apr 27, 2018 at 8:35

3 Answers 3

1

Try this:

<?php
$vars = [
    'consectetur' => 'BINGO',
    'diam' => 'BINGO'
];

$str = "Lorem ipsum dolor sit amet, {consectetur} adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus {diam}. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum.";

$parsed = preg_replace_callback("/\{([\w\_]{1,})\}/", function ($match) use ($vars) {
    return array_key_exists($match[1], $vars) ? $vars[$match[1]] : '';
}, $str);

echo $parsed;

https://3v4l.org/BbtbK

Or as you seem to want, which is kind of useless.

echo preg_replace("/\{(.*?)\}/", 'BINGO', $str);

https://3v4l.org/AHGXP

Sign up to request clarification or add additional context in comments.

1 Comment

This is still the best answer so far. :)
0

You can use preg_replace

<?php
$string = 'your String';
$pattern = '/\{(.*?)\}/';
$replacement = 'BINGO';
echo preg_replace($pattern, $replacement, $string);
?>

1 Comment

Sorry for last wrong version. I have corrected it. Try this
0

You can use preg_match() with str_replace -

$str = "Lorem ipsum dolor sit amet, {consectetur} adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus {diam}. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum.";

preg_match('{(.*)}', $str , $matches);

print_r($matches);

output - Array ( [0] => {hello:{}{}yooohooo} [1] => {hello:{}{}yooohooo} ) 

Use this output inside str_replace() function of php

echo str_replace($matches[0],"Your Replacing string",$str);

OR

You can use preg_replace() function

 $replace_str = preg_replace('{(.*)}', "Your Replacing string", $str);

   echo $replace_str;

I hope this will help you!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.