1

So I have code that goes something like this:

$sql = "SELECT * FROM LIST"
$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?

2
  • Why are you assigning a variable in the middle of the echo? What do you use $text for? Commented May 25, 2015 at 23:26
  • Oh I guess that just doesn't need to be there. I just put that in there from when I Iearned about preg_replace, I'll edit that out of my question. Thanks Commented May 25, 2015 at 23:29

2 Answers 2

2

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>";
Sign up to request clarification or add additional context in comments.

1 Comment

This works just fine for what I'm doing. I use money_format for the numbers and I use preg_replace to change the numbers to font. I could just use an if statement to make this work right?
0

You can do multiple replacements by giving an array of patterns and replacements:

$info = preg_replace(array('/\b0\b', '\b1\b'), array('NA', 'NA2'), $row['info']);

So your code would look like:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.