Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Feb 2012
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Preg_replace excluding strings inside tags

    OK, Ive been working on a little project for quite some time, I have everything working so far with a preg_replace function that takes words and replacement words as an array then runs through a string to replace them.

    I am stuck as always with excluding tag data. As much as I search on phpnet I am not understanding how to exclude between an opening tag and closing tag.

    tags I want to exclude are all, but the important ones are

    <a>
    <img >

    I was actually writing a it to replace the values with temp holders, then run strip tags on the result, then preg_match on the results, then only use the remaining holders to actually replace the values in the starting text. Then I thought that was quite a bit of overhead for somthing that I believe can be resolved with an exeption.

    Thanks in advance

    Chris

  • #2
    New to the CF scene
    Join Date
    Feb 2012
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts
    OK I figured it out.. here is a simple function to replace keywords witrh whatever values you liike without breaking html code.

    Code:
    $occurance= 1 ;
    function replaceText($input,$replacer,$replace,$occurance){
    	$replacer = "/(?!(?:[^<]+>|[^>]+<\/a>))\b(".$replacer.")\b/is";
                 $occurance = ($occurance >0  ? $occurance : -1);
    	$updated = preg_replace($replacer, $replace, $input, $occurance); 
    	return $updated;
    }


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •