Welcome to WebmasterWorld Guest from 54.145.209.107

Forum Moderators: coopster & jatar k

ereg replace with a variable

Is this possible?

   
7:19 pm on Jun 30, 2008 (gmt 0)

10+ Year Member



I have a regular expression that looks for everything between brackets, and returns the values in between the brackets.

$original = "This is the [replace] statement";

$new = ereg_replace('\\[(.*)\\]', '\\1', $original);

What I'm essentially looking to do is replace the contents of the brackets with the value of a variable of the same name.

Example:

$replacetext = "desired text";

$original = "This is the [replacetext] statement";

$new = ereg_replace('\\[(.*)\\]', '$\\1', $original);

//$new = "This is the desired text statement";

Any suggestions?

7:35 pm on Jun 30, 2008 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member



$new = ereg_replace('#(\[[^\]]+\])#',$replacetext,$original);
7:42 pm on Jun 30, 2008 (gmt 0)

10+ Year Member



Thanks - but what I'm looking for is something dynamic (so that I don't have to do a custom ereg for each element I'm trying to replace.
7:56 pm on Jun 30, 2008 (gmt 0)



I don't know about ereg_replace, but I believe you should be able to do this via the 'e' modifier of preg_replace [php.net] (to evaluate the pattern as PHP code):

$new = preg_replace('/\[(.*)\]/e', '$${1}', $original);
8:48 pm on Jun 30, 2008 (gmt 0)

10+ Year Member



Receptional Andy, that's exactly what I was looking for!

Thanks!

8:57 pm on Jun 30, 2008 (gmt 0)



I'm no expert in either PHP or regex, so I would recommend a look through the preg_replace manual entry in any case. I can already see potential changes to the line I posted (e.g. no need for braces around the back-reference), and if you know the pattern to match is always a (lowercase) letter, then perhaps the below would be more efficient (I'm not sure on that, though):

$new = preg_replace('/\[([a-z]+)\]/e', '$$1', $original); 
6:45 pm on Jul 7, 2008 (gmt 0)

WebmasterWorld Administrator coopster is a WebmasterWorld Top Contributor of All Time 10+ Year Member



Actually, it would be most efficient to locate anything that is not the closing bracket. Everything else looks just fine.

$new = preg_replace('/\[([^\]]+)\]/e', '$$1', $original);
 

Featured Threads

Hot Threads This Week

Hot Threads This Month