Basically I have a block of html that I want to echo to the page and the html has the $ sign in it and the php thinks it is a variable so $1 is treated as the variable not the value and is not displayed.
There is the standard answers here but none are working: PHP: How to get $ to print using echo
My next idea is to split the string at the $ and echo each part out.
Here is the code I have tried echo and print.
foreach ($rows as $rowmk) {
$s = $rowmk->longdescription;
//$s = str_replace('$', '@', $s);
$s = str_replace('$', '\$', $s);
//echo "$s" . "<br>";
print $s;
}
All help appreciated.
OK I solved by using the character code value for $
foreach ($rows as $rowmk) {
$s = $rowmk->longdescription;
$s = str_replace('$', '$', $s);
echo $s . "<br>";
}
I figured I should just post it anyway.
Thanks,
Mat
You're doing it in the wrong place. Variable interpolating is done when double quoted string literal (which in your case is stored within $rowmk->longdescription
is daclared. Once it's done, you can't really do anything to get your $
s back.
Solution, do proper escaping, when you declare the string.
Or you could echo string literal using single quotes...
<?php
echo 'Give me $1';
?>
will print:
Give me $1
PHP string docs:
http://php.net/manual/en/language.types.string.php
Side note - the link you provide has many answers that would work perfectly. How are you applying them in a way that doesn't work?
Just use a single quoted string.
$foo = 'Hello';
echo '$foo'; // $foo
echo "$foo"; // Hello
I assume you read your rows from a database. Dollar Signs inside these strings will not be interpolated by php. Here's a little test script to try it out:
// you'd first have to set the three variables according to your database
$dbh = new PDO($DSN, $DB_USER, $DB_PASS);
// create a table and insert a string containing a dollar sign
$dbh->exec('CREATE TABLE IF NOT EXISTS some_text ( longdescription VARCHAR( 255 ))');
$dbh->exec('INSERT INTO some_text ( longdescription ) VALUES ( "10 $" )');
// query all the data from the table
$query =$dbh->query("SELECT * FROM some_text");
$rows = $query->fetchAll(PDO::FETCH_CLASS);
// loop over all the rows (as in your example) and output the rows
// no problem at all
foreach ($rows as $rowmk) {
$s = $rowmk->longdescription;
echo $s . "<br>";
}
I did it using this
echo "$" . "VariableName";