PHP - Replace With Dynamic Variable In Preg_replace
Hi
I'm trying the following code: Code: [Select] $t = '12<-- AB_C -->'; $AB_C = 'abc'; echo preg_replace('/\<-- ([A-Z_]+) --\>/', "$$1", $t);I want to get "12abc" , but it outputs: 12$AB_C , so, it not recognize the replacement as dynamic variable. Is it any way to use the matched word in preg_replace() as a variable, or dynamic variable? Similar TutorialsI need a way of just replacing those three characters (",',\,/) with nothing, any ideas? I'm trying to use preg_replace but I can't get it working. function replaceContent($sContent) { $aReplaceTags = array( "'\[MENU-CARD\](.*?)\[/MENU-CARD\]'is" => '\\1', "'\[CONTACT-FORM\]'is" => "Contactform", ); return preg_replace(array_keys($aReplaceTags), array_values($aReplaceTags), $sContent); } This works great however when I change '\\1' into a function the output of '\\1' will always be 1. function replaceContent($sContent) { $aReplaceTags = array( "'\[MENU-CARD\](.*?)\[/MENU-CARD\]'is" => $this->loadMenuCard('\\1'), "'\[CONTACT-FORM\]'is" => "Contactform", ); return preg_replace(array_keys($aReplaceTags), array_values($aReplaceTags), $sContent); } Anyone knows what I am doing wrong? i get the following error in the comments in wordpress blog..: Warning: preg_replace() [function.preg-replace]: No ending delimiter '~' found in /home/doughhhh/public_html/wp-content/themes/upload/includes/theme-comments.php on line 75 the content of the file is: Code: [Select] <?php // Fist full of comments if (!function_exists("custom_comment")) { function custom_comment($comment, $args, $depth) { $GLOBALS['comment'] = $comment; ?> <li <?php comment_class(); ?>> <a name="comment-<?php comment_ID() ?>"></a> <div id="li-comment-<?php comment_ID() ?>" class="comment-container"> <div class="comment-head"> <?php if(get_comment_type() == "comment"){ ?> <div class="avatar"><?php the_commenter_avatar($args) ?></div> <?php } ?> <div class="reply"> <?php comment_reply_link(array_merge( $args, array('depth' => $depth, 'max_depth' => $args['max_depth']))) ?> </div><!-- /.reply --> </div><!-- /.comment-head --> <div class="comment-entry" id="comment-<?php comment_ID(); ?>"> <span class="arrow"></span> <div class="comment-info"> <div class="left"><span class="name"><?php the_commenter_link() ?></span></div> <div class="right"> <span class="date"><?php echo get_comment_date(get_option( 'date_format' )) ?> <?php _e('at', 'themejunkie'); ?> <?php echo get_comment_time(get_option( 'time_format' )); ?></span> <span class="perma"><a href="<?php echo get_comment_link(); ?>" title="<?php _e('Direct link to this comment', 'themejunkie'); ?>">#</a></span> <span class="edit"><?php edit_comment_link(__('Edit', 'themejunkie'), '', ''); ?></span> </div> <div class="clear"></div> </div> <?php comment_text() ?> <?php if ($comment->comment_approved == '0') { ?> <p class='unapproved'><?php _e('Your comment is awaiting moderation.', 'themejunkie'); ?></p> <?php } ?> </div><!-- /comment-entry --> </div><!-- /.comment-container --> <?php } } // PINGBACK / TRACKBACK OUTPUT if (!function_exists("list_pings")) { function list_pings($comment, $args, $depth) { $GLOBALS['comment'] = $comment; ?> <li id="comment-<?php comment_ID(); ?>"> <span class="author"><?php comment_author_link(); ?></span> - <span class="date"><?php echo get_comment_date(get_option( 'date_format' )) ?></span> <span class="pingcontent"><?php comment_text() ?></span> <?php } } if (!function_exists("the_commenter_link")) { function the_commenter_link() { $commenter = get_comment_author_link(); if ( preg_match( '~]* class=[^>]+>~', $commenter ) ) {$commenter = preg_replace( '~(]* class=[\'"]?)~', '\\1url ' , $commenter ); } else { $commenter = preg_replace( '~(<a )/', '\\1class="url "~' , $commenter );} echo $commenter ; } } if (!function_exists("the_commenter_avatar")) { function the_commenter_avatar($args) { $email = get_comment_author_email(); $avatar = str_replace( "class='avatar", "class='photo avatar", get_avatar( "$email", $args['avatar_size']) ); echo $avatar; } } ?> help! [attachment deleted by admin] This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=343073.0 preg_replace() asks that "Delimiter must not be alphanumeric or backslash" in the pattern. So I changed $new_text = preg_replace($_POST['withthis'] ,$_POST['withthis'],$_POST['text']); to this $replacethis = $_POST['replacethis']; $new_text = preg_replace("/$replacethis/",$_POST['withthis'],$_POST['text']); It works fine, but out of curiosity, is there any way to have the POST variable as a parameter directly, and why does it not work? Just to try it, I attempted: "/$_POST['withthis']/" and $_POST["/'withthis'/"] and both do not work. str_replace is a better option I think, but I am just trying to get a better understanding of this delimiter rule. Thanks for your time! Hi ! I'd like to count all occurences in "$thiscodestring" into a "dynamic?" array and print it out after the end of the loop, how do I assign the variablenames dynamically ? $query = "SELECT codes, status FROM table"; while ($row = mysql_fetch_assoc($result)) { $thiscodestring = $row[codes]; // looks like "a1 c2 d3 10 15 1 a1 a1"; $singlecodes = explode(" ", $thiscodestring); foreach($singlecodes as $thiscode) { $$thiscode[count] = $$thiscode[count] + 1; } } After all Mysql-Stuff is done I'd like to print out the counted codes, for example the code "a1" was found 100 times in all querys then $$a1[count] should be 100, c2 was found 15 times, then $$c2[count] should be 15 and so on. Question: How do I tell php to assign a "dynamic" variable with the name of the found string which was exploded (in this example a1, c2, d3... ) before ?! $$ does not seem to work. And how can I then print_r() the value if I dont know the name ? Thanks ! Hello. I want to create some variables dynamically. I have this so far: for($i = 1; $i <= 4 ; $i++){ $a = 'member' . $i; $$a = array(); } Does that give me this 4 arrays?: $member1, $member2, $member3 and $member4? Of course I want some process inside of the loop, but that would depend on the variables. Would that work? thanks! <?php $foo = 5; $too = 7; ${"foo"}++; ${"too"}++; echo $foo; echo '<br />' . $too; $my_var_name = "foo"; ${$my_var_name}++; echo $foo; ?> I understand the part that $my_var_name is going to increment $foo. But I don't understand that when we used ${"foo"} we did not add the $ sign with it. But when we use ${$my_var_name} we have to add another $ sign. why is that? hi guys I just could not find the answer on forum. I have a url like this http://www.example.com/deal.php?id=367 and my question is : how can i use curl function to get the html and the id value which is 367 thanks OK, what I am trying to do is generate a dynamic variable name. I want to setup a foreach statement that will generate variable names based on an array of data. $numbers = array('one', 'two', 'three', 'four', 'five', 'six', 'seven'); foreach ($numbers as $number) { } What I need, is for a bunch of variables to be generated and filled with content. $variable_one_label = "Blah"; $variable_two_label = "Blah Again"; How can I generate the dynamic variable based on the array value? I have a form that inserts information into a mysql, the only prolem is I need to add different surrounding html to the information when entering it into the database depending what the value is...(essentially I want to store font color around different levels) How would I define the same variable with different information depending on the value? The information is called using: if ($_SERVER['REQUEST_METHOD'] == 'POST') { $editLEVEL=$_POST['level']; I want it so if 'Level1' is the posted value then $editLEVEL would be '<color=1>$editLEVEL</color>' but if 'Level2' is the posted value the $editLEVEL would be '<color=2>$editLEVEL</color>' If you dont understand just let me know I'll try explain best I can. Hello, I'm working on a dynamic text form (I guess thats what its called). Basically, I have a html page that echos in some PHP code. What the PHP code does is show different strings of text depending on a variable: Code: [Select] <PHP? $brief1_info = "brief info goes here"; $brief1 = 0; if (isset($_POST['brief1Go'])) { $brief1 = $brief1 + 1; } else if (isset($_POST['brief1Back'])) { $brief1 = $brief1 - 1; } $breif1Controller = " <form action=\"".$_SERVER['PHP_SELF']."\" method=\"post\"> <input type=\"submit\" name=\"brief1Back\" id=\"brief1Back\" value=\"BACK\" /> </form> <form action=\"".$_SERVER['PHP_SELF']."\" method=\"post\"> <input type=\"submit\" name=\"brief1Go\" id=\"brief1Go\" value=\"CONTINUE\" /> </form>"; if($brief1 == 0){ $brief1_info = "<b>Welcome Commander,</b> you are currently viewing the Mission Control Brief page, here you can view all your missions that you need to complete in order to advance through your prestiges. You will need to follow your briefs carefully in order to succeed. <br /><br /> "; } else if($brief1 == 1){ $brief1_info = "Okay, let me show you around the place ..."; } else if($brief1 == 2){ $brief1_info = "brief is on 2"; } ?> The problem is, the BACK and CONTINUE buttons don't work. If $brief1 equals 0, and the user presses continue, the is should go to 1, and the brief1_info string is changed (so some different text shows in my html). It actually works when brief1 is on '0', but when its on 1 and the user pressed continue, the brief1 is changed to 1, but because the submit button refreshes the page, the variable is re-read again, and thus is reset back to 0. Is there a way around this? Or is there a better method than what I'm doing? Thanks Hi all, here's my code: Code: [Select] <?php foreach ($_SESSION['topping'] as $value) { echo "<tr><td width='30%'>Topping</td><td width='50%'>$value</td><td width='20%'><select name='notopping'>"; foreach ($_SESSION['cupcake'] as $number) { '<option name="notoppings[]" value="'.$number.'">".$number."</option>'; } echo "</select></td></tr>"; } ?> $_SESSION['cupcake'] is a value from either 6, 12, 24 or 36. What I want to do is put them into a drop down box (second foreach) as the value and the displayed value - counting up from 1 (so 1,2,3,4,5,6 or up to 12,24 etc). Also by creating this as an array, does this mean than for each topping (say Vanilla and Chocolate) the value dynamically created can be used on the next page by using $_POST['notoppings'] to display each type (two different numbers - one for Vanilla and one for Chocolate). Does that make sense? Thanks! Jason The situation is that I have a large string with some identifiers to say "replace me" with something else. My goal is to replace the values, but if one replacement includes one of the other keys, I don't want to replace it.
For example:
<?php $str = 'some blob ~abc~ followed by ~def~'; $arr_orig = array( '~abc~', '~def~' ); $arr_new = array( 'value~def~', 'blah' ); echo str_replace( $arr_orig, $arr_new, $str ); ?>This will echo: some blob valueblah followed by blah But that's not what I'm trying to accomplish. Basically, I want ~abc~ to be replaced with the literal: value~def~ and for the ~def~ that happens to be part of that string to NOT be replaced. I hope what I'm asking is clear. Basically, preg_replace/str_replace with arrays seems no different than just doing a FOR loop and replacing ~abc~ and then ~def~. But that's not what I need. I'm hoping that if ~abc~ is replaced with text that happens to be another identifier -- ~def~, ~xyz~, whatever -- that this already replaced text is not again replaced. Is there a built-in function to do something like this? If not, should I just parse the whole string and count characters or something? Seems like a pain (and slow!) Hi i wrote a find and replace code but my code replace last value of array and skip the first, second.... values in the array. Please give me an idea because i stack with this code. Regards $KeyWord = explode("\n", $RowGetWords['KEYWORDS']); $Replace = explode("\n", $RowGetWords['ReplaceTo']); for($i=0; $i<count($KeyWord); $i++){ $pattern = $KeyWord[$i]; $replace = "<a href=\"" .$URL. "\" target=\"_blank\" >" .$Replace[$i]. "</a>"; $html = str_replace($pattern, $replace, $Row['MessageBody']); } Folks, I need help (Php code ) to generate a Dynamic Text on a Base Image. What i want to do is, to make this Image as header on my Site and to make this Header Specific to a Site, i want to Add the Domain Name on the Lower Left of the Image. Got the Idea? Here is the Image link: Quote http://img27.imageshack.us/i/shoppingheader1.jpg/ PHP Variable that holds the Domain name is: $domain All i need the Dynamic PHP Codes that i can put on all my sites to generate this Text on Image (Header) Dynamically... May Anyone Help me with this Please? Cheers Natasha T. Hi, I'm kind of new to PHP and very new to Regular Expressions and I was wondering if someone could help run through this code snippet from a callback function in a Joomla plugin called Affliates Feed. So far I have this is passed a pointer to variable item (I understand this is effectively the same as passing the variable but a lot less CPU intensive. Creates an array with keys and values Now the for loop I am stuck with, I understand the interation through the array. But what is preg_replace returning and why pass it back that way hasn't it already done its job? Can any one help? And please feel free to be as basic as possible :help: Thanks, Adam Code: [Select] function gardening(&$item) { #renaming categories, not the most efficient use for example strtolower first, and use only lowercase in the rename array $rename=array( ' Gardening?' => '', 'Climber Plants' => 'Climbing Plants', 'Seeds.*Bulbs' => 'Seeds Bulbs', 'Plant protection' => 'Horticultural goods', 'Garden structures' => 'Garden buildings',); foreach ( $rename as $k => $v ) { list($item['menu_1'],$item['menu_2'])=preg_replace("#$k#",$v,array($item['menu_1'],$item['menu_2'])); } $item['menu_1']=ucfirst(strtolower($item['menu_1'])); $item['menu_2']=ucfirst(strtolower($item['menu_2'])); $item['menu_3']=ucfirst(strtolower($item['menu_3'])); $item['menu_4']=ucfirst(strtolower($item['menu_4'])); } Hi everyone, how do i add and ampersand symbol into preg_replace preg_replace("/[^a-zA-Z0-9\s\-\'\,\.\_]/" where do i place the symbol? & After days of searching I found this thread http://www.phpfreaks.com/forums/index.php?topic=236954.0 that helped me do what I was trying to do. I've gotten the code to create and rename my html document but I can't figure out how to use the preg_replace part. This is my template with the 3 variables I want to replace with values from a form. Code: [Select] <html> <head> <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body> <?php include_once('content.php') ?> </body> <SCRIPT language="JavaScript" SRC="javascript.js"></SCRIPT> <script type="text/javascript"> function nametitle(){ parent.iframe1.document.getElementById("div1").innerHTML = "VARIABLE1 <br>VARIABLE2"; parent.iframe1.document.getElementById("quotes").innerHTML = "VARIABLE3"; } </script> </html> I've spent hours reading and trying to understand how to make it work but it's a little over my head. Could someone help me with this? Thanks, I'm trying to search a string for all occurences of a pattern, then append text after that pattern. The example is:
SUM("foo") as "bar"
and have it display as:
SUM("foo") over() as "bar"
The "SUM" could be any SQL aggregate and be case insensitive. So For bonus points, let's say the valid aggregates are array('SUM', 'MAX', 'MIN', 'AVG'). My plan right now is to figure it out for SUM, then loop it replacing the aggregate.
This is what I have so far... and it is not working.
$l= 'SUM("foo") as "bar"';
$l=preg_replace('/([^"]+")/','\0 over()',$l);
Thanks,
Ryan
|