简体   繁体   中英

How do I properly use str_replace here?

I'm trying to take data in a HTML table column and format it with PHP depending on it's value. The column tracks movement, so if it's a positive value I'd like to add an upward facing arrow (↑) before the value. If it's a negative number, I'd like to replace the '-' with a downward facing arrow (↓). I've set up an IF/ELSE statement that checks the value of the data. I can get the upward arrow to show up without issue, but I'm having trouble formatting negative values the way I'd like. I've researched the issue on Stack and started using str_replace. The way I have it set up now, I can get a negative value like -2 to be replaced with ↓2, but right next to the ↓2 the -2 remains (like this ↓2 -2). I somewhat understand why this is happening, I just don't know how to get it to do what I want. Here is my IF statement:

if ($row['move'] > 0) {
    $arrow = '↑ ';
} else if ($row['move'] < 0) {
    $arrow = str_replace('-', '&#8595; ', $row['move']);
} else {
    $arrow = '';
}

And here is how I print my data (some of it, to avoid irrelevant code). $style changes the color of the text:

echo "<td{$style}>" . $arrow.$row["move"] . "</td><td>"

Thank you for whatever help you can offer!

I wouldn't use str_replace , in fact, but instead take the absolute value of $row['move'] .

// decide which arrow to use
if ($row['move'] > 0) {
    $arrow = '&#8593; ';
} else if ($row['move'] < 0) {
    $arrow = '&#8595; ';
} else {
    $arrow = '';
}

// remove the sign (if it's there)
$move = abs($row['move']);

// output
echo "<td{$style}>{$arrow}{$move}</td><td>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM