php - Inject code after X paragraphs but avoiding tables -


i inject code after x paragraphs, , pretty easy php.

public function inject($text, $paragraph = 2) {      $exploded = explode("</p>", $text);     if (isset($exploded[$paragraph])) {         $exploded[$paragraph] = '             mycode             ' . $exploded[$paragraph];          return implode("</p>", $exploded);     }     return $text; } 

but, don't want inject $text inside <table>, how avoid this?

thanks

i'm bit crazy, go patterns lazy, time i'm going hazy.

$input = 'test <table><p>wuuut</p><table><p>lolwut</p></table></table> <p>foo bar</p> test1 <p>baz qux</p> test3'; # input $insertafter = 2; # insert after n p tags $code = 'code'; # code want insert  $regex = <<<'regex' ~ # let's define (?(define)    (?p<table>                     # match nested table tags       <table\b[^>]*>          (?:             (?!</?table\b[^>]*>).          |             (?&table)          )*       </table\s*>    )    (?p<paragraph>                 # match nested p tags       <p\b[^>]*>          (?:             (?!</?p\b[^>]*>).          |             (?&paragraph)          )*       </p\s*>    ) ) (?&table)(*skip)(*fail)           # let's skip table tags | (?&paragraph)                     # , match p tags ~xsi regex;  $output = preg_replace_callback($regex, function($m)use($insertafter, $code){     static $counter = 0; # counter     $counter++;     if($counter === $insertafter){ # should explain?         return $m[0] . $code;     }else{         return $m[0];     } }, $input);  var_dump($output); # let's see we've got 

online regex demo online php demo

references:


Comments

Popular posts from this blog

c++ - How to add Crypto++ library to Qt project -

jQuery Mobile app not scrolling in Firefox -

How to use vim as editor in Matlab GUI -