views:

56

answers:

2

Say I have a string like this:

$string = 'The /*quick*/ brown /*fox*/ jumped over the lazy /*dog*/.';

How can I use a regular expression to find the occurrences of /* */ and replace each value like so:

/*quick*/ with the value of $_POST['quick']
/*fox*/ with the value of $_POST['fox']
/*dog*/ with the value of $_POST['dog']

I have tried with preg_replace using this pattern: ~/\*(.+)\*/~e

But it does not seem to be working for me.

+4  A: 

The pattern (.+) is too greedy. It will find the longest match i.e. quick*/ brown /*fox*/ jumped over the lazy /*dog, so it won't work.

If there will be no * appear between /* and */, then use:

preg_replace('|/\*([^*]+)\*/|e', '$_POST["$1"]', $string)

Otherwise, use a lazy quantifier:

preg_replace('|/\*(.+?)\*/|e', '$_POST["$1"]', $string)

Example: http://www.ideone.com/hVUNA.

KennyTM
`preg_replace('|/\*([^*]+)\*/|e', '$_POST["$1"]', $string)` Beautifully put
RobertPitt
preg_replace('|/\*([^*]+)\*/|e', '$_POST["$1"]', $string) did the job great,thank you.
Mike
A: 

You can generalize this (PHP 5.3+, dynamic functions):

$changes = array('quick' => $_POST['quick'],
                 'fox'   => $_POST['fox'],
                 'dog'   => $_POST['dog']   );

$string = 'The /*quick*/ brown /*fox*/ jumped over the lazy /*dog*/.';

echo preg_replace(
        array_map(function($v){return'{/\*\s*'.$v.'\s*\*/}';}, array_keys($changes)),
        array_values($changes),
        $string
     );

if you want to have fine control over what gets replaced. Otherwise, KennyTM already solved this.

Regards

rbo

rubber boots