This has got me very confused. Here is the code but it is not doing what it should do!!

echo "<span class='vehicle_table_normal'>";$str_bodystyle=str_replace("," ,"<br />",$bodystyle);$str_bodystyle=str_replace("-" ,"&#45; ",$bodystyle);$str_bodystyle=str_replace(" - " ," &#45; ",$bodystyle);echo $str_bodystyle;

The first replace is the most important for display purposes at this moment. The next two are because I like things to look the same. but none of the three replaces are doing anything!

What on earth am I doing wrong?

Dani AI

Generated

Short answer: earlier replacements never "stacked" because each call used the original string as the subject, so the final assignment simply overwrote the previous ones. correctly pointed out a variable misuse, but using .= to concatenate the three replacement results will append strings rather than perform sequential replacements. The proper fixes are (A) run each replacement on the result of the previous call, or (B) do all replacements in one call with arrays.

A — single-call (array) approach:

$search  = [',', ' - ', '-'];
$replace = ['<br/>', ' &#45; ', '&#45;'];
$processed = str_replace($search, $replace, $bodystyle);
echo '<span class="vehicle_table_normal">' . $processed . '</span>';

B — sequential re-assignment (feed the previous result into the next call):

$out = str_replace(',', '<br/>', $bodystyle);
$out = str_replace(' - ', ' &#45; ', $out);
$out = str_replace('-', '&#45;', $out);
echo '<span class="vehicle_table_normal">' . $out . '</span>';

Notes and cautions:

  • Do the longer pattern (' - ') before the shorter ('-') to avoid accidental partial matches. The array order in approach A respects this.
  • If $bodystyle comes from user input, escape where appropriate. Inserting raw <br/> after running htmlspecialchars() will be escaped, so plan escaping and tag insertion carefully.
  • Close the HTML you open (the first post echoed an opening <span> but did not show a closing tag).
  • PHP manual for str_replace documents the array form and behavior: str_replace — PHP Manual.

Recommended Answers

All 2 Replies

Hi,

The problem with the codes are your variable names they are all the same. The script will only show the very last one, because it will override the first two. If you want it to work, then use .= (concatenating assignment operator) .

something like this..

$str_bodystyle = ""; //prevent any errors in php 5.3 and above.

$str_bodystyle .= str_replace("," ,"<br/>",$bodystyle);
$str_bodystyle .=str_replace("-" ,"&#45; ",$bodystyle);
$str_bodystyle .=str_replace(" - " ," &#45; ",$bodystyle);
echo $str_bodystyle;

you genius veedeoo !!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.