开发者

PHP Coding Restrict Preg_replace function from multiple tags

I have a great little script that will search 开发者_StackOverflow中文版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.


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜