Page 1 of 1

Disabling preg_replace to affect text inside textarea tags?

Posted: Wed Jun 11, 2008 6:42 am
by kaisellgren
Hi!

I have a website and I am replacing some text on it using preg_replace. The problem is that it should not replace any text within textarea tags. How would I do preg_replace_if_not_inside_textarea?

Any ideas or help?

Re: Disabling preg_replace to affect text inside textarea tags?

Posted: Wed Jun 11, 2008 9:40 am
by superdezign
You could avoid making one long regex, you could tokenize the string, making textarea tokens and miscellaneous text tokens.

Code: Select all

function tokenizeTextareas($content)
{
  $startToken = '<textarea>';
  $endToken = '</textarea>';
  $tokens = array();
 
  while(($startPosition = strpos($content, $startToken)) !== false) {
    $tokens[] = substr($content, 0, $startPosition);
    $content = substr($content, $startPosition);
 
    if (($endPosition = strpos($content, $endToken)) !== false) {
      $tokens[] = substr($content, 0, $endPosition + strlen($endToken));
      $content = substr($content, $endPosition );
    }
  }
 
  if (!empty($content)) {
    $tokens[] = $content;
  }
 
  return $tokens;
}
Untested, but should work to help you tokenize your data.

Re: Disabling preg_replace to affect text inside textarea tags?

Posted: Wed Jun 11, 2008 9:47 am
by kaisellgren
Thanks :)