jamessw Posted January 14, 2010 Share Posted January 14, 2010 Is it possible to define a variable within preg_replace? This would allow me to use them later. I've tried things like setting the replacement pattern to '$variable = $1', which I'm not surprised didn't work. Any ideas? Quote Link to comment https://forums.phpfreaks.com/topic/188421-capturing-back-references-from-preg_replace-as-variables/ Share on other sites More sharing options...
trq Posted January 14, 2010 Share Posted January 14, 2010 You can use an array within the replacement argument. Quote Link to comment https://forums.phpfreaks.com/topic/188421-capturing-back-references-from-preg_replace-as-variables/#findComment-994705 Share on other sites More sharing options...
salathe Posted January 14, 2010 Share Posted January 14, 2010 Can you give more details (a quick snippet example) of what you're trying to achieve, even if it doesn't work? Quote Link to comment https://forums.phpfreaks.com/topic/188421-capturing-back-references-from-preg_replace-as-variables/#findComment-994754 Share on other sites More sharing options...
jamessw Posted January 14, 2010 Author Share Posted January 14, 2010 Here's an example- $string = 'First worked | FAIL | '; $pattern = '%(.+) \| (.+) \| .+%i'; $replacement = '{$first = $1}{$second = $2}'; echo preg_replace($pattern, $replacement, $string); echo $first; How would I use an array in the replacement pattern? Quote Link to comment https://forums.phpfreaks.com/topic/188421-capturing-back-references-from-preg_replace-as-variables/#findComment-994945 Share on other sites More sharing options...
jamessw Posted January 15, 2010 Author Share Posted January 15, 2010 Ok. Using the /e at the end of the search pattern, you can have preg_replace execute the code define("THENAME","$1), and then set a variable to that constant. Quote Link to comment https://forums.phpfreaks.com/topic/188421-capturing-back-references-from-preg_replace-as-variables/#findComment-995335 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.