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[^>]*>). | (?¶graph) )* </p\s*> ) ) (?&table)(*skip)(*fail) # let's skip table tags | (?¶graph) # , 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
Post a Comment