我需要一些以下代码的帮助。我在桌子上有一个字段,我需要更换各种标签,并且我已经确定了定位特定区域所需的正则表达式模式。这段代码将它们拉出来并将它们剥离成我想要的格式但它分配给它们所有相同的" 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);
}
}
}
答案 0 :(得分:0)
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);