Extracting $1 from preg_replace

Hi there,

When using the preg_replace() function you can capture elements of the input string into strings $1, $2 and so on, so that they can be used in the output.

What I want to do is store the contents of $1 into a variable so that I can use it outside of the preg_replace function.

Is this possible?

Here’s what I’m working on:

$text = preg_replace('/\\[DOWNLOAD=([-a-z0-9._~:\\/?#@!$&\\'( )*+,;=%]+)](.+?)\\[\\/DOWNLOAD]/i', '<a href="download.php"><img src="/images/download.png" /></a>', $text);
  $file = $1
  return[$text, $file]

What I want the end user to do is be able to type a short code, which will create a download link to the file indicated in the short code.

So, for example, [DOWNLOAD=“example.pdf”], would create the link, then store the filename into a string, then pass that to another script which could then select the file from the server.

I hope that makes sense.

Thanks in advance for your help.


you should take a look at: preg_match

int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )

If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.