preg_replace始终返回原始字符串

时间:2018-07-17 19:16:49

标签: php regex preg-replace

我想用'<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 个答案:

答案 0 :(得分:0)

您不应该为此使用正则表达式...但是您的问题是,.在没有s修饰符的情况下不匹配新行。

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

https://regex101.com/r/pV7XRd/1/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