Re: Regular expressions
| From: | Jochem Maas | Date: | Tue, 03 Feb 2004 17:40:33 +0000 |
| Subject: | Re: Regular expressions | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-176704@lists.php.net to get a copy of this message | ||
Pete,
you can probably do what you want with preg_replace_callback:
http://nl2.php.net/manual/en/function.preg-replace-callback.php
only the function call will be set up slightly differently; namely you don't pass the callback reference directly, instead the callback function that is called recieves an array with all the matches in - which you can then use to spit something back out.
---
alternatively (actually this looks like the easier way to do it!) use preg_replace(), with the 'e' modifier tagged onto the end of the replacement expression: the 'e' modifier causes the expression to be evaluated as PHP.
http://nl2.php.net/manual/en/function.preg-replace.php
http://nl2.php.net/manual/en/pcre.pattern.modifiers.php
something like:
$pattern = '/\[link="([[:graph:]]+)"]/';
$replacement = "/check_this_out('\1')/e";
$output = preg_replace($pattern, $replacement, $output);
pete@doberad.com wrote:
Hi there, I have serious probems resolving regular expressions. I wish to replace a substring with a given pattern with results of a function with a backreference used as argument. SAMPLE: function check_this_out($somevalue) { $url_array = ''; $i=0; $query = "SELECT SomeRow FROM SomeTable WHERE SomeRowID='$somevalue';"; $result = mysql_query($query) or die (mysql_error().$query); $someow = mysql_fetch_array($result); var_dump($somerow); return ($query); } $output = 'aliquyam erat, sed diam voluptua. [link="21"]This is a test[/link]'; echo ($output); echo ('<br />'); $output = ereg_replace('\[link="([[:graph:]]+)"]',check_this_out('\1'), $output); echo ('<br />'); var_dump ($output); $output2 = 'aliquyam erat, sed diam voluptua. [link="21"]This is another test[/link]'; echo ($output); echo ('<br />'); $output2 = ereg_replace('/\[link="([[:graph:]]+)"]/',check_this_out('\1'), $output); echo ('<br />'); var_dump ($output2); The problem is, that although the $query string in this example will echo as "SELECT SomeRow FROM SomeTable WHERE SomeRowID='21';", where $somevalue has been replaced by '21' as a result by the regular expressions, it will eventually render as "SELECT SomeRow FROM SomeTable WHERE SomeRowID='\1';" when mysql is called, return the row with SomeRowID='\1', which incidently is not the row I want... I tried type casting to no avail. Has anybody experienced similar problems or know how to get around this? My php version is somewhere between 4.3.4 and 4.3.5... a 4.3.5-dev... Best Regards Peter Normann ?>