Kyle Dunne Kyle Dunne - 1 year ago 103
MySQL Question

preg_replace specific sql columns in php

So I have code that goes something like this:

$result = $conn->query($sql);

if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {

echo "<div class=\"leftcol\"><p>".preg_replace('/\b0\b/', 'NA', $row["info"])."</p></div>
<div class=\"rightcol\"<p>".preg_replace('/\b0\b/', 'NA', $row["stuff"])."</p></div>";

That works for them rows fine. But then I run into the problem where I need to use multiple replaces on $row["info"] AND $row["stuff"]. I would like to replace \b1\b with another word but at the same time as \b0\b.

What works best for this? Would there be something that does this better outside of the P tag or SQL info all together?

Answer Source

Just do the replaces before you echo the html, eg:

while($row = $result->fetch_assoc()) {

    $text = preg_replace('/\b0\b/', 'NA', $row["info"]);
    $text = preg_replace('/\b1\b/', 'NA2', $text);
    $text = preg_replace('/\b2\b/', 'NA3', $text);

    $text2 = preg_replace('/\b1\b/', 'NA2', $row["stuff"]);

    echo "<div class=\"leftcol\"><p>".$text."</p></div>
          <div class=\"rightcol\"<p>".$text2."</p></div>";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download