加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 17:30:25 所属栏目:PHP教程 来源:网络整理
导读:我想在X段后注入一些代码,这对于php来说非常简单. public function inject($text,$paragraph = 2) { $exploded = explode("/p",$text); if (isset($exploded[$paragraph])) { $exploded[$paragraph] = ' MYCODE ' . $exploded[$paragraph]; return implode("
我想在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
      <tableb[^>]*>
         (?:
            (?!</?tableb[^>]*>).
         |
            (?&table)
         )*
      </tables*>
   )
   (?P<paragraph>                 # To match nested p tags
      <pb[^>]*>
         (?:
            (?!</?pb[^>]*>).
         |
            (?&paragraph)
         )*
      </ps*>
   )
)
(?&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?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读