1

I have a String which contains substrings which I have to replace. The substrings are stored in an array. When I loop through the array everything works fine, until the array has more than 120 entries.

foreach ( $activeTags as $k => $v ) {
  $find = $activeTags[$k]['Tag']['tag'];
  $replace = 'that';
  $pattern = "/\#\#[a-zA-Z][a-zA-Z]\#\#.*\b$find\b.*\#\#END_[a-zA-Z][a-zA-Z]\#\#|$find/"; 
  $sText = '<p>Do not replace ##DS## this ##END_DS## replace this.</p>';

  $sText = preg_replace_callback($pattern, function($match) use($find, $replace){
    if($match[0] == $find){
      return($replace);
    }else{
      return($match[0]);
    }
  }, $sText);
}

when count($activeTags) == 121 i only get an empty string.

Has onyone an idea why this happens?

5
  • Try to var_dump your array? Commented Jan 13, 2014 at 11:09
  • manually setting the array with less than 121 entries works fine, dynamically too. Commented Jan 13, 2014 at 11:26
  • 1
    Possibly there is something odd with your 121st tag. Commented Jan 13, 2014 at 11:47
  • nope, the 121tag is correct. i replaced it with other tags and still the problem was tag no121 Commented Jan 13, 2014 at 12:12
  • Can you add the $activeTags array content with 121 entries ? Commented Jan 13, 2014 at 13:26

1 Answer 1

1

Try this improved pattern:

$pattern = "~##([a-zA-Z]{2})##.*?\b$find\b.*?##END_\1##|$find~s";

Description

Regular expression visualization

Discussion

The ~s flag indicates that dot (.) should match newlines. In your example, p tags are metionned. So I guess its an html fragment. Since newlines are alloed in html, I have added the ~s flag. More over, I have made the pattern more readable by:

  • using custom pattern boundaries: / becomes ~, you avoid escape anything...
  • replacing duplicate subpatterns: [a-zA-Z][a-zA-Z] becomes [a-zA-Z]{2}
  • taking advantage of the sequence ##DS## ##END_DS##. I use a backreference (\1) for matching what was found in the first matching group (Group 1 in the above image).
Sign up to request clarification or add additional context in comments.

1 Comment

@user2641845 No you can ... don't you ? :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.