Home:ALL Converter>Copy string with regex

Copy string with regex

Ask Time:2012-09-21T19:42:12         Author:VORiAND

Json Formatter

I have hundreds of variables with this structure:

$bsdatA = $_POST['bsdat_a'];
$bsdatB = $_POST['bsdat_b'];


The problem is that i have to add isset() function to every of it, like this:

$bsdatA = isset($_POST['bsdat_a']) ? $_POST['bsdat_a'] : '';
$bsdatB = isset($_POST['bsdat_b']) ? $_POST['bsdat_b'] : '';


This is a manual copy and paste on every single line... Can it be done via regular expression? If yes, can someone write me down the exact formula? It would save me lot of time.

Thank you very much.

Author:VORiAND,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/12529867/copy-string-with-regex
Berry Langerak :

Well, not a regex, because I don't see how that'd help, but here's a function that can simplify the coding by a lot:\n\n<?php\nfunction postvar($index){\n return isset($_POST[$index]) ? $_POST[$index] : '';\n}\n\n$bsdatA = postvar('bsdat_a');\n\n\nI'd use postvar('bsdat_a') directly, instead of putting the outcome in a variable, by the way, because you risk ending up with a lot of variables you're only going to use once. If you're absolutely sure you want to have $bsdatA and $bsdatB as local variables, then I would suggest using a loop:\n\n<?php\nforeach( range('A', 'Z') as $current ) {\n ${'bsdat'.$current} = postvar('bsdat_'.strtolower($current));\n}\n\n\nBut then, that's just scary :)\n\nEDIT: Ah, you're talking about an existing script, and you want to change it to include a lot of isset() calls? Sorry I didn't pick up on that.\n\nYou could replace $_POST with an object that implements ArrayAccess. This way, you can also log POST variables that are called, but not used:\n\n<?php\nclass PostVars implements ArrayAccess {\n protected $vars;\n public $log;\n\n public function __construct($vars) {\n $this->vars = $vars;\n }\n\n public function offsetGet($offset) {\n if(!isset($this->vars[$offset])) {\n $this->log[] = $offset;\n }\n return $this->vars[$offset];\n\n }\n\n public function offsetExists($offset) {\n return isset($this->vars[$offset]);\n }\n\n public function offsetSet($offset, $value) {\n // readonly.\n }\n\n public function offsetUnset($offset) {\n // readonly.\n }\n}\n\n$_POST = array('bsdat_a' => 'bar', 'bsdat_b' => null);\n\n$_POST = new PostVars($_POST);\n\necho $_POST['bsdat_a'];\necho $_POST['bsdat_b'];\n",
Khôi :

I assume that you are trying to change the code using an IDE that supports Regex Replaces:\n\nHere's the regex for Eclipse:\n\nFind:\n\n\\$(\\w+) = \\$_POST\\['(\\w+)'\\]\n\nReplace:\n\n$1 = isset(\\$_POST['$2']) ? \\$_POST['$2'] : '';",
Tim Pietzcker :

$result = preg_replace('/\\$(\\w+)\\s+=\\s+\\$_POST\\[\\'([^\\']+)\\'\\];/', \n '$\\1 = isset($_POST[\\'\\2\\']) ? $_POST[\\'\\1\\'] : \\'\\';', $subject);\n",