代码之家  ›  专栏  ›  技术社区  ›  Abdus Sattar Bhuiyan

preg_replace始终返回原始字符串[重复]

  •  0
  • Abdus Sattar Bhuiyan  · 技术社区  · 6 年前

    这个问题已经有了答案:

    我想替换 '<tbody>' 具有 '<thead>' 形式:

    <table class="table table-bordered table-responsive" style="width: 100%;">
    <tbody>
    

    这是我的代码:

    $reg_exp = "/(^<table.+.(?:[n])?(?:.+)?)(<tbody>)/";
    $replace_with = "/1<thead>";
    echo $input = '<table class="table table-bordered table-responsive" style="width: 100%;">
    <tbody>';
    $final = preg_replace($reg_exp, $replace_with, $input);
    
    var_dump($final);
    

    它打印:

    string(83) "<table class="table table-bordered table-responsive" style="width: 100%;">
    <tbody></tbody></table>
    

    我想不出哪里不对!拜托,有人能指导我怎么做?谢谢

    1 回复  |  直到 6 年前
        1
  •  0
  •   user3783243    6 年前

    你不应该用正则表达式…但是你的问题是 . 如果没有 s 修饰语。

    $reg_exp = "/(^<table.+.(?:[n])?(?:.+)?)(<tbody>)/s";
    

    https://regex101.com/r/pV7XRd/1/ VS https://regex101.com/r/pV7XRd/2/

    你也应该使用 $1 \\1 换一个。

    $reg_exp = "/(^<table.+.(?:[n])?(?:.+)?)(<tbody>)/s";
    $replace_with = '$1<thead>';
    $input = '<table class="table table-bordered table-responsive" style="width: 100%;">
    <tbody>';
    $final = preg_replace($reg_exp, $replace_with, $input);
    var_dump($final);
    

    https://3v4l.org/srNiQ