脚本宝典收集整理的这篇文章主要介绍了php – 在X段之后注入代码但避免使用表,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
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; }
但是,我不想在< table>中注入我的$text,那么如何避免这种情况呢?
谢谢
$input = 'test <table><p>wuuut</p><table><p>LOLwut</p></table></table> <p>foo bar</p> test1 <p>baz qux</p> test3'; # Some input $insertAfter = 2; # Insert after N p tags $code = 'CODE'; # The code we want to insert $regex = <<<'regex' ~ # let's define something (?(DEFINE) (?P<table> # To match nested table tags <table\b[^>]*> (?: (?!</?table\b[^>]*>). | (?&table) )* </table\s*> ) (?P<paragraph> # To match nested p tags <p\b[^>]*> (?: (?!</?p\b[^>]*>). | (?¶graph) )* </p\s*> ) ) (?&table)(*SKIP)(*FaiL) # Let's skip table tags | (?¶graph) # And match p tags ~xsi regex; $output = preg_replace_callback($regex,function($m)use($insertAfter,$code){ static $counter = 0; # A counter $counter++; if($counter === $insertAfter){ # Should I explain? return $m[0] . $code; }else{ return $m[0]; } },$input); var_dump($output); # Let's see what we've got
Online regex demo
Online php demo
参考文献:
> Reference – What does this regex mean?
> What does the “[^][]” regex mean?
> Verbs that act after backtracking and failure
> Is there a way to define custom shorthands in regular expressions?
以上是脚本宝典为你收集整理的php – 在X段之后注入代码但避免使用表全部内容,希望文章能够帮你解决php – 在X段之后注入代码但避免使用表所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。