I'm very new to regular expressions in PHP, and don't understand very much of it. Maybe someone can help me with this case: In an html page I insert comments like <!-- food_chicken --> Code (markup): and <!-- drink_water --> Code (markup): Now I want to replace whatever "category"_"item" with it's variable $category['item'] Can anyone help me make a regular expression from this, or maybe it can be done otherwise, that's good too Thanks in advance, have a good year! Koen
I enjoy puzzling around with php Here's a simple solution: <?php $food["chicken"] = "plate"; $drink["water"] = "glass"; $text = "randomtexthere<br /> <!-- food_chicken --><br /> randomtexthere<br /> <!-- food_chicken --><br /> randomtexthere<br /> randomtexthere <!-- drink_water -->randomtexthere<br />"; $regpattern = "<!-- (.*) -->"; preg_match_all($regpattern,$text,$resultarray,PREG_PATTERN_ORDER); // Filter out only the unique tags: $results = array_unique($resultarray[1]); foreach($results as $regresult){ /* $regresult will be in the 'food_chicken' format, so let's split food_chicken to 2 seperate values: food & chicken */ $charpos = strpos($regresult,"_"); //Search for _ $varname = substr($regresult,0,$charpos); //Get 'food' $itemname = substr($regresult,$charpos + 1); //Get 'chicken' // Check if var & item actually exist if(!isset($$varname)) continue; $realvar = $$varname; if(!isset($realvar["$itemname"])) continue; // Replace the "<!-- food_chicken -->" tags with the corresponding value.. $oldtag = "<!-- $regresult -->"; //Rebuild tag $newvalue = "<strong>" . $realvar[$itemname] . "</strong>"; $text = str_replace($oldtag,$newvalue,$text); } //Output End Result... echo $text; ?> PHP: This comes with some safety issues though, as you would have to prevent users from displaying any <!-- --> tags... Something like an XSS vulnerability could potentially lead to someone displaying and accessing some important variables.. Another method you could and might want to consider is looping through the already existing variables (like $food), and use str_replace to automatically search any existing tags. (Much safer as you can define which variables may be displayed/replaced) Greetings from The Netherlands
Thank you very very much I will try out both, and see what's the best! Greetings back from the Netherlands , Happy new year! Koen *EDIT*: Here is what I used: Now I have all the categories and items in one variable (with arrays). foreach($category AS $key => $value) { $process = str_replace("<!-- $key -->", $value, $skin); } PHP: thanks for the second tip, because that's a bit easier for me