GordonFreeman
GordonFreeman

Reputation: 3

How do I write function using reg ex through preg_replace()

assert(isCorrect('') === true);
assert(isCorrect('()') === true); 
assert(isCorrect('{()}') === true);
assert(isCorrect('{()}{}') === true); 
assert(isCorrect('(())') === true);
assert(isCorrect('{({({({()})})})}') === true); 
assert(isCorrect('{(})') === false);

this i have result for preg_match:

function isCorrect($source){
    return (bool)preg_match('~^((\(([^)(}{]|(?1))*\))|\{(?3)*\})*$~', $source);
}

Now I have the same thing only through preg_replace();

Upvotes: 0

Views: 85

Answers (2)

user557597
user557597

Reputation:

Doing recursion could be a little tricky.
For sure you have to account for balanced pairs separately or it doesn't work.

If you expect just characters (){}, this one.

 # '~(\((?:(?>(?1))|)\)|\{(?:(?>(?1))|)\})~'

 (                      # (1 start)
      \(
      (?:
           (?> (?1) )
        |  
      )
      \)
   |  
      \{
      (?:
           (?> (?1) )
        |  
      )
      \}
 )                      # (1 end)

Or, if you expect other characters besides (){} inside, this one.

 #  '~(\((?:(?>[^(){}]+)|(?1))*\)|\{(?:(?>[^(){}]+)|(?1))*\})~'

 (                           # (1 start)
      \(
      (?:
           (?> [^(){}]+ )
        |  
           (?1) 
      )*
      \)
   |  
      \{
      (?:
           (?> [^(){}]+ )
        |  
           (?1) 
      )*
      \}
 )                           # (1 end)

Upvotes: 1

Jonny 5
Jonny 5

Reputation: 12389

^((\(([^)(}{]|(?1))*\))|\{(?3)*\})*$ is the recursive pattern from my comment yesterday which checks if the string is composed of correctly nested ({}) / {()} from ^ start to $ end.

Assuming you want to replace all, that are correctly nested with empty string "" change it to:

$str = preg_replace('~\(([^)(}{]|(?0))*\)|\{(?1)*\}~', "", $str);

Test at regex101; Test at eval.in; Regex FAQ

Please rephrase your question, what acutally you're going to do, if that's not it.

Upvotes: 0

Related Questions