How to print $ with php - php

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

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

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.

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>";
}

You can use "\$"
ex:
"\$stringvalue"

I did it using this
echo "$" . "VariableName";

Related

How can I use regex to catch unquoted array indices in PHP code and quote them?

PHP 7.2 upgraded undefined constant errors from a notice to a warning, with advice that in future they will return a full-on error instead.
I am trying to identify a way to fix these via scripting, ideally via a regex that I can run to parse each PHP file on a site, find all offending bits of code, and fix them.
I've found multiple examples of how to fix one variant, but none for another, and it's that one that I'm looking for help with.
Here's an example file:
<?php
$array[foo] = "bar";
// this should become
// $array['foo'] = "bar"
echo "hello, my name is $array[foo] and it's nice to meet you";
// would need to become
// echo "hello, my name is " . $array['foo'] . " and it's nice to meet you";
?>
I've seen a lot of options to identify and change the first type, but none for the second, where the undefined constant is within a string. In that instance the parser would need to:
Replace $array[foo] with $array['foo']
Find the entire variable, end quotes beforehand, put a . either side, and then reopen quotes afterwards
Edit: ideally one regexp would deal with both examples in the sample code in one pass - i.e. add the ticks, and also add the quotes/dots if it identifies it’s within a string.
$array[foo] = "bar";
// this should become
// $array['foo'] = "bar"
Yes, this has always triggered a notice and has always been poor practice.
echo "hello, my name is $array[foo] and it's nice to meet you";
// would need to become
// echo "hello, my name is " . $array['foo'] . " and it's nice to meet you";
No, this style has never triggered a notice and does not now. In fact, it's used as an example in the PHP documentation. PHP is never going to remove the ability to interpolate array variables in strings.
Your first case is easy enough to catch with something like this:
$str = '$array[foo] = "bar";';
echo preg_replace("/(\\$[a-z_][a-z0-9_]*)\\[([a-z][a-z0-9_]*)\\]/", "$1['$2']", $str);
But of course needs to be caught only outside of a string.
As with any complex grammar, regular expressions will never be as reliable as a grammar-specific parser. Since you're parsing PHP code, your most accurate solution will be to use PHP's own token parser.
$php = <<< 'PHP'
<?php
$array[foo] = "bar"; // this line should be the only one altered.
$array['bar'] = "baz";
echo "I'm using \"$array[foo]\" and \"$array[bar]\" in a sentence";
echo 'Now I\'m not using "$array[foo]" and "$array[bar]" in a sentence';
PHP;
$tokens = token_get_all($php);
$in_dq_string = false;
$last_token = null;
$output = "";
foreach ($tokens as $token) {
if ($last_token === "[" && is_array($token) && $token[0] === 319 && !$in_dq_string) {
$output .= "'$token[1]'";
} elseif (is_array($token)) {
$output .= $token[1];
} else {
if ($token === "\"") {
$in_dq_string = !$in_dq_string;
}
$output .= $token;
}
$last_token = $token;
}
echo $output;
Output:
<?php
$array['foo'] = "bar"; // this line should be the only one altered.
$array['bar'] = "baz";
echo "I'm using \"$array[foo]\" and \"$array[bar]\" in a sentence";
echo 'Now I\'m not using "$array[foo]" and "$array[bar]" in a sentence';
This code would need some edge cases accounted for, such as when you are intentionally using a constant as an array index.
This isn't perfect, but it should be safe to run multiple times (example)
$str = 'echo "hello, my name is $array[foo] and it\'s nice to meet you";';
echo preg_replace_callback('/\".*(\$.*\[[^\'].*[^\']\]).*\"/', function($match) {
$search = ['[', ']'];
$replace = ["['", "']"];
$array = '" . ' . str_replace($search, $replace, $match[1]) . ' . "';
return str_replace($match[1], $array, $match[0]);
}, $str);
What the regex does is it limits itself to double quoted strings (\"). Then we look for $var[val], without the ticks '. Once we've captured it, we can run it through a callback that does a two-stage str_replace. The first wraps our matched $var[val] with double quotes and inserts the ticks, while the second inserts it into the whole string, using the regex found match
It won't do some things nicely tho. If you have $array[foo] $array[bar], it will wind up as
" . $array['foo'] . "" . $array['bar'] . "
Not pretty, but still valid code

How to combine two string in PHP?

My PHP Code:
$username="jack";
$var= mt_rand(1000,100000 );
$data="$username _Deleted_$var";
echo $data;
Expected Output: jack_Deleted_91111
Original Output: jack _Deleted_91111
$data = "{$username}_Deleted_$var";
or
$data = $username."_Deleted_".$var;
. is in php symbol for concatenating strings, { and } used in string means that anything between this symbol is a variable.
Try this:
$data=$username . '_Deleted_' . $var;
See, if that solves your white space issue.

How to assign " to a variable in php?

I want to get date using date function but the date should comes between " ". I want to assign " to a variable so that i can get my output by combining the two variables:
$td=""";
$td2="".date("m/d/Y")."";
$td3=""";
$date="$td"."$td2"."$td3";
Please help...?
If you don't want to escape them, just wrap them in a single quote instead:
$td = '"';
$td2 = '"'.date("m/d/Y").'"';
$td3 = '"';
$date = $td.$td2.$td3;
You need to escape them
$td = "\"";
With the backslash, the character is treated as a character by any means necessary and is ignored by php, it wont be used to limiting strings or someting like that.
Try
$td=""";
OR
$td = "\"";
Use backslash or single quotes .
You have to use "\" before " in your $td and $td3 variable.
$td="\"";

PHP, explode multiple words and prefix them with a character [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Add a prefix to each item of a PHP array
I try to use Boolean mode full text search.
If a user types more than two words, it supposes to make like this.
Search Keyword : Apple Macbook Air
Result : +Apple +Macbook +Air
So, I made a php command to make this happen, but didn't work.
$ArrayKeywords = explode(" ", $b_keyword);
for($i = 0; $i < sizeof($ArrayKeywords); $i++)
$array_keyword = '+"$ArrayKeywords[$i]" ';
can you tell me how to make this happen?
Can also do (demo)
echo preg_replace('(\w+)', '+$0', 'Apple Macbook Air');
Why not just do this:
$keyword = '+' . trim(str_replace(' ',' +',$b_keyword));
Don't really need to for loop there
// trims off consecutive spaces in the search term
$b_keyword = preg_replace('/\s+/', ' ', $b_keyword);
$ArrayKeywords = explode(" ", $b_keyword);
echo '+' . implode(' +', $ArrayKeywords);
I see there's a bit of a misunderstanding how variables inside strings work.
You may have learned that anything inside single quotes is parsed as is and inside double quotes the variables' contents are printed, like so:
$foo = 'bar';
echo 'foo: $foo'; // result: foo: $foo
echo "foo: $foo"; // result: foo: bar
But, you can't combine the two methods; putting double quotes inside single quotes doesn't make the variable's contents printed. The double quotes work only if the entire string is delimited by them. Therefore the following won't work:
echo 'foo: "$foo"'; // result: foo: "$foo"
Expanding this to your case, you can just replace the single quotes with double quotes and drop the inner double quotes.
$array_keyword .= "+$ArrayKeywords[$i] ";
Also note that you have to concatenate the new words into the variable (.=), otherwise the variable is overwritten on each loop.
Side note: it's much easier to use a foreach loop than a for loop when looping through arrays:
$ArrayKeywords = explode(" ", $b_keyword);
$array_keyword = '';
foreach( $ArrayKeywords as $keyword ) {
$array_keyword .= '+$keyword ";
}
If you want it for tabs, newlines, spaces, etc.
echo preg_replace('(\s+)', '$0+', ' Apple Macbook Air');
//output: +Apple +Macbook +Air

How to remove all leading zeroes in a string

If I have a string
00020300504
00000234892839
000239074
how can I get rid of the leading zeroes so that I will only have this
20300504
234892839
239074
note that the number above was generated randomly.
ltrim:
$str = ltrim($str, '0');
(string)((int)"00000234892839")
you can add "+" in your variable,
example :
$numString = "0000001123000";
echo +$numString;
Similar to another suggestion, except will not obliterate actual zero:
if (ltrim($str, '0') != '') {
$str = ltrim($str, '0');
} else {
$str = '0';
}
Or as was suggested (as of PHP 5.3), shorthand ternary operator can be used:
$str = ltrim($str, '0') ?: '0';
Don't know why people are using so complex methods to achieve such a simple thing! And regex? Wow!
Here you go, the easiest and simplest way (as explained here: https://nabtron.com/kiss-code/ ):
$a = '000000000000001';
$a += 0;
echo $a; // will output 1
Regex was proposed already, but not correctly:
<?php
$number = '00000004523423400023402340240';
$withoutLeadingZeroes = preg_replace('/^0+/', '', $number)
echo $withoutLeadingZeroes;
?>
output is then:
4523423400023402340240
Background on Regex:
the ^ signals beginning of string and the + sign signals more or none of the preceding sign. Therefore, the regex ^0+ matches all zeroes at the beginning of a string.
I don't think preg_replace is the answer..
old thread but just happen to looking for this today. ltrim and (int) casting is the winner.
<?php
$numString = "0000001123000";
$actualInt = "1123000";
$fixed_str1 = preg_replace('/000+/','',$numString);
$fixed_str2 = ltrim($numString, '0');
$fixed_str3 = (int)$numString;
echo $numString . " Original";
echo "<br>";
echo $fixed_str1 . " Fix1";
echo "<br>";
echo $fixed_str2 . " Fix2";
echo "<br>";
echo $fixed_str3 . " Fix3";
echo "<br>";
echo $actualInt . " Actual integer in string";
//output
0000001123000 Origina
1123 Fix1
1123000 Fix2
1123000 Fix3
1123000 Actual integer in tring
A short hack can be to use round() it will remove leading zeros.
echo round('00020300504'); //20300504
Ajay Kumar offers the simplest echo +$numString;
I use these:
echo round($val = "0005");
echo $val = 0005;
//both output 5
echo round($val = 00000648370000075845);
echo round($val = "00000648370000075845");
//output 648370000075845, no need to care about the other zeroes in the number
//like with regex or comparative functions. Works w/wo single/double quotes
Actually any math function will take the number from the "string" and treat it like so. It's much simpler than any regex or comparative functions.
I saw that in php.net, don't remember where.
Im Fixed with this way.
its very simple. only pass a string its remove zero start of string.
function removeZeroString($str='')
{
while(trim(substr($str,0,1)) === '0')
{
$str = ltrim($str,'0');
}
return $str;
}
Assuming you want a run-on of three or more zeros to be removed and your example is one string:
$test_str ="0002030050400000234892839000239074";
$fixed_str = preg_replace('/000+/','',$test_str);
You can make the regex pattern fit what you need if my assumptions are off.
This help?

Categories