php - 在 X 段之后注入(inject)代码但避免使用表格

标签 php regex explode

我想在 X 段之后注入(inject)一些代码,这使用 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;
}

但是,我不想注入(inject)我的 $text<table> 里面,那么如何避免这种情况呢?

谢谢

最佳答案

我有时有点疯狂,有时我会选择懒惰的模式,但这次我想要一些朦胧的东西。

$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[^>]*>).
         |
            (?&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

引用资料:

关于php - 在 X 段之后注入(inject)代码但避免使用表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23180154/

相关文章:

php - Zend Translate 会自动检测语言吗?

php - Azure应用程序服务不使用新的/更改的文件

mysql - 从 bash 获取特定文件名

phpexplode() 将文本文件中的所有值存储到索引 [0]

php - 添加具有小时和分钟值的字段

PHP preg_replace $1 没有空格

python - re.search() 挂起

c# - C# 中的正则表达式问题

php - 展开文件名以分隔名称和扩展名在 PHP 中不起作用?

php - 为什么ajax @post到达php页面时为空