By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,373 Members | 1,763 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,373 IT Pros & Developers. It's quick & easy.

Regular Expressions

P: 3
Hi guys,
i need replace all specified characters (in this case its "N") between the square parentheses by the question mark ("?"). I have dynamic/variable string mask, for example something like CON[NNNN][YYYY] and as output i need to get CON[????][YYYY]. So simply explained replace everything between parentheses by specified sign as many times as the length of match is.

I'm looking for something like:

As expected, this pattern replaces just match [NNNN] by one ? instead of [????].

Thanks for any reply.
Nov 7 '11 #1
Share this Question
Share on Google+
5 Replies

Expert Mod 5K+
P: 8,639
not sure if there’s a better way, but as a temporary work-around you can use the match (from a preg_match()) in a str_replace() to simply replace all Ns and then replace the result of that in the original string.
Nov 8 '11 #2

P: 3
I don't know if i exactly understand what you mean. Can you write down some simple example of your imagine? Do you mean sthg like this?

str_replace(preg_match('/(\[)(N+)(\])/', '?', $mask));

Cause this will replace match with single question mark again. Thanks very much.
Nov 8 '11 #3

Expert Mod 5K+
P: 8,639
something along
Expand|Select|Wrap|Line Numbers
  1. // somewhat pseudo code
  2. preg_match('#\[(N+)\]#', $str, $matches);
  3. $x   = str_replace('N', '?', $match1)
  4. $str = str_replace($match0, $x, $str);
Nov 8 '11 #4

P: 3
works great with some differences... final function:

Expand|Select|Wrap|Line Numbers
  1.     protected function prepare_mask_to_edit($identifier,$required_mask=null) {
  2.     $mask = (!is_null($required_mask)) ? $required_mask : $this->mask;
  3.     preg_match('#\[('.$identifier.'+)\]#', $mask,$matches);
  4.         if(is_array($matches)) {
  5.             $question_mark = str_replace($identifier,'?',$matches[1]);
  6.             $editable_mask = str_replace($matches[1], $question_mark, $mask);
  7.         }
  8.     return $editable_mask;
  9.     }
Nov 8 '11 #5

Expert Mod 5K+
P: 8,639
note: $matches is always an array. the questions is whether the array length is correct or if there are any findings.
Nov 8 '11 #6

Post your reply

Sign in to post your reply or Sign up for a free account.