php – 在X段之后注入代码但避免使用表

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 在X段之后注入代码但避免使用表脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在X段后注入一些代码,这对于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;
}

但是,我不想在< 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[^>]*>).
         |
            (?&amp;table)
         )*
      </table\s*>
   )
   (?P<paragraph>                 # To match nested p tags
      <p\b[^>]*>
         (?:
            (?!</?p\b[^>]*>).
         |
            (?&paragraph)
         )*
      </p\s*>
   )
)
(?&table)(*SKIP)(*FaiL)           # Let's skip table tags
|
(?&paragraph)                     # 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,请注明来意。