0

I want to replace '<tbody>' with '<thead>' form:

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

And Here is my code:

$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);

It prints:

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

I can't figure out whats wrong! Please, someone can guide me on how i can do this? Thanks

Abdus Sattar Bhuiyan
  • 3,016
  • 4
  • 38
  • 72

1 Answers1

0

You shouldn't use a regex for this...BUT your issue is a . doesn't match new lines without the s modifier.

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

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

You also should use $1 or \\1 for the replacement.

$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

user3783243
  • 5,368
  • 5
  • 22
  • 41