homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

ereg replace with a variable
Is this possible?

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

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.


$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)

$new = ereg_replace('#(\[[^\]]+\])#',$replacetext,$original);


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

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.

Receptional Andy

 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)

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


Receptional Andy

 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)

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);

Global Options:
 top home search open messages active posts  

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved