Disabling preg_replace to affect text inside textarea tags?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
kaisellgren
DevNet Resident
Posts: 1675
Joined: Sat Jan 07, 2006 5:52 am
Location: Lahti, Finland.

Disabling preg_replace to affect text inside textarea tags?

Post 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?
Last edited by kaisellgren on Wed Jun 11, 2008 9:47 am, edited 1 time in total.
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Re: Disabling preg_replace to affect text inside textarea tags?

Post 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.
User avatar
kaisellgren
DevNet Resident
Posts: 1675
Joined: Sat Jan 07, 2006 5:52 am
Location: Lahti, Finland.

Re: Disabling preg_replace to affect text inside textarea tags?

Post by kaisellgren »

Thanks :)
Post Reply