Regular Expressions

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • exidas
    New Member
    • Nov 2011
    • 3

    Regular Expressions

    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:
    preg_replace("/\[N+\]/","?","CON[NNNN][YYYY]");

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

    Thanks for any reply.
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    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.

    Comment

    • exidas
      New Member
      • Nov 2011
      • 3

      #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(pre g_match('/(\[)(N+)(\])/', '?', $mask));

      Cause this will replace match with single question mark again. Thanks very much.

      Comment

      • Dormilich
        Recognized Expert Expert
        • Aug 2008
        • 8694

        #4
        something along
        Code:
        // somewhat pseudo code
        preg_match('#\[(N+)\]#', $str, $matches);
        $x   = str_replace('N', '?', $match1)
        $str = str_replace($match0, $x, $str);

        Comment

        • exidas
          New Member
          • Nov 2011
          • 3

          #5
          works great with some differences... final function:

          Code:
          	protected function prepare_mask_to_edit($identifier,$required_mask=null) {
          	$mask = (!is_null($required_mask)) ? $required_mask : $this->mask;
          	preg_match('#\[('.$identifier.'+)\]#', $mask,$matches);
          		if(is_array($matches)) {
          			$question_mark = str_replace($identifier,'?',$matches[1]);
          			$editable_mask = str_replace($matches[1], $question_mark, $mask);
          		}
          	return $editable_mask;
          	}

          Comment

          • Dormilich
            Recognized Expert Expert
            • Aug 2008
            • 8694

            #6
            note: $matches is always an array. the questions is whether the array length is correct or if there are any findings.

            Comment

            Working...