0

I have a string which contains several keywords in square backets which I want to identify, extract, and replace with something else:

For example:

'You will win [winnings] or [slice].'

I want to identify all the terms within the squares, take those terms and replace them with certain values.

So it should end up like this:

'You will win 100 or 95%.'

Any ideas?

j0k
  • 22,303
  • 28
  • 77
  • 86
ojsglobal
  • 497
  • 6
  • 28
  • Possible dublicate: http://stackoverflow.com/questions/2403122/regular-expression-to-extract-text-between-square-brackets – Peon Dec 28 '12 at 13:22

3 Answers3

3

piece of cake

$search = array('[winnings]', '[slice]');
$replace = array(100, '95%');

echo str_replace($search, $replace, 'You will win [winnings] or [slice].');
Maxim Krizhanovsky
  • 25,260
  • 5
  • 51
  • 86
1
$replacements = array(
    'winnings' => '100'
    , 'slice'  => '95%'
    , 'foobar' => 'Sean Bright'
);

$subject = '[foobar], You will win [winnings] or [slice]!';

$result = preg_replace_callback(
    '/\[([^\]]+)\]/',
    function ($x) use ($replacements) {
        if (array_key_exists($x[1], $replacements))
            return $replacements[$x[1]];
        return '';
    },
    $subject);

echo $result;

Note that this will completely fall apart if you have unbalanced brackets (i.e. [[foo])

For PHP versions less than 5.3:

$replacements = array(
    'winnings' => '100'
    , 'slice'  => '95%'
    , 'foobar' => 'Sean Bright'
);

function do_replacement($x)
{
    global $replacements;

    if (array_key_exists($x[1], $replacements))
        return $replacements[$x[1]];
    return '';
}

$subject = '[foobar], You will win [winnings] or [slice]!';

$result = preg_replace_callback(
    '/\[([^\]]+)\]/',
    'do_replacement',
    $subject);

echo $result;
Sean Bright
  • 114,945
  • 17
  • 134
  • 143
0

And if you want to use a regex to find matches:

$content = "You will win [winnings] or [slice].";
preg_match_all('/\[([a-z]+)\]/i', $content, $matches);

$content = str_replace($matches[0], array('100', '95%'), $content);

var_dump($content);
j0k
  • 22,303
  • 28
  • 77
  • 86