我需要一些关于以下代码的帮助。我在表上有一个字段,我需要替换各种标签,并且我已经确定了针对特定区域所需的正则表达式模式。这段代码将它们拉出并将它们剥离为我想要的格式,但是......它在正文中为它们分配了相同的"imageId"——数组中的最后一个。我知道它没有以正确的方式循环,只需要另一双眼睛来观察它。我觉得如果它通过 Body 并一次替换一个标签而不是在 for 循环的中间,它可能会做它应该做的事情。目前字段正文如下所示:
<text:image id="12345" blah blah blah />
lots of text here
<text:image id="123456" blah blah blah />
lots of text here
<text:image id="7890" blah blah blah />
我希望它看起来像这样:
<text:image id="12345"/>
lots of text here
<text:image id="123456" />
lots of text here
<text:image id="7890" />
这是代码:
$textToReplace2 = mysqli_query($conn, "SELECT id, body from t1");
while($row2 = $textToReplace2->fetch_array()) {
$t1_id = $row2["id"];
$body = $row2["body"];
$oldBody = $body;
$pattern = '#(text:image id=)"'d+(.*)(/>)#';
preg_match_all($pattern, $body, $matches);
foreach ($matches[0] as $match) {
$id=$match;
preg_match('#'d+#', $id, $nextMatches);
foreach ($nextMatches as $nextMatch) {
$imageId=$nextMatch;
$newBody = preg_replace($pattern, 'ID:'.$imageId, $body);
$newEscapedBody = mysqli_real_escape_string($conn, $newBody);
$update2 = "UPDATE T1 SET body = '$newEscapedBody' where id = '$t1_id'";
$updateResult2 = mysqli_query($conn, $update2);
}
}
}
Yeuch!
有几种方法可以改善这一点。我手头没有我的正则表达式测试器,但类似的东西......
while($row2 = $textToReplace2->fetch_array()) {
$t1_id = $row2["id"];
$body = $row2["body"];
$replace='$1>'; // some experimentation needed to find correct index
$new=preg_replace('#(<text':image id="('d+)")([^>]+)>#U', $replace, $body);
$newEscapedBody = mysqli_real_escape_string($conn, $new);