0

I have a great little script that will search a file and replace a list of words with their matching replacement word. I have also found a way to prevent preg_replace from replacing those words if they appear in anchor tags, img tags, or really any one tag I specify. I would like to create an OR statement to be able to specify multiple tags. To be clear, I would like to prevent preg_replace from replacing words that not only appear in an anchor tag, but any that appear in an anchor,link,embed,object,img, or span tag. I tried using the '|' OR operator at various places in the code with no success.

    <?php
$data = 'somefile.html';
$data = file_get_contents($data);
$search = array ("/(?!(?:[^<]+>|[^>]+<\/a>))\b(red)\b/is","/(?!(?:[^<]+>|[^>]+<\/a>))\b(white)\b/is","/(?!(?:[^<]+>|[^>]+<\/a>))\b(blue)\b/is");
$replace = array ('Apple','Potato','Boysenberry');
echo preg_replace($search, $replace, $data);?>
print $data;
?>

looking at the first search term which basically says to search for "red" but not inside :

"/(?!(?:[^<]+>|[^>]+<\/a>))\b(red)\b/is"

I am trying to figure out how I can somehow add <\/link>,<\/embed>,<\/object>,<\/img> to this search so that preg_replace doesn't replace 'red' in any of those tags either.

2

1 Answer 1

0

Something like this?:

<?php
   $file = 'somefile.html';
   $data = file_get_contents($file);
   print "Before:\n$data\n";
   $from_to = array("red"=>"Apple",
                    "white"=>"Potato",
                    "blue"=>"Boysenberry");
   $tags_to_avoid = array("a", "span", "object", "img", "embed");
   $patterns = array();
   $replacements = array();

   foreach ($from_to as $from=>$to) {
     $patterns[] = "/(?!(?:[^<]*>|[^>]+<\/(".implode("|",$tags_to_avoid).")>))\b".preg_quote($f
rom)."\b/is";
     $replacements[] = $to;
   }

   $data = preg_replace($patterns, $replacements, $data);

   print "After:\n$data\n";
   ?>

Result:

Before:
<a href="red.html">red</a>
<span class="blue">red</span>
blue<div class="blue">white</div>
<div class="blue">red</div>

After:
<a href="red.html">red</a>
<span class="blue">red</span>
Boysenberry<div class="blue">Potato</div>
<div class="blue">Apple</div>
Sign up to request clarification or add additional context in comments.

Comments

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.