How to have constants evaluated in strings? [duplicate] - php

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Include constant in string without concatenating
How can I get a constant to be evaluated in a string like variables are?
$foo = "like";
define('BAR', 'fish');
// None of these give me 'I like to eat fish on Tuesday.'
echo "I $foo to eat BAR on Tuesday.";
echo "I $foo to eat {BAR} on Tuesday.";
echo 'I $foo to eat BAR on Tuesday.';
// This works but is undesirable
echo 'I $foo to eat '.BAR.' on Tuesday.';

The only way I know this'd works (which you may already be aware of) is by doing:
<?php
$foo = "like";
define('BAR', 'fish');
$constants = get_defined_constants();
echo "I $foo to eat {$constants['BAR']} on Tuesday.";
?>
which prints:
I like to eat fish on Tuesday.

As far as I know that isn't possibile. Check this answer here at SO, it contains useful workarounds if concatenation is so undesirable too you! Include constant in string without concatenating

of course there is no way. And no need.

Related

How to make the first letter of a word uppercase? [duplicate]

This question already has answers here:
Uppercase first letter and rest lower
(6 answers)
Closed 7 years ago.
I have this word:
katii
But I want the first character in uppercase K. How can I do this?
Use function usfirst
string ucfirst ( string $str )
You can use below as prescribed by php.net
<?php
$foo = 'hello world!';
$foo = ucfirst($foo); // Hello world!
$bar = 'HELLO WORLD!';
$bar = ucfirst($bar); // HELLO WORLD!
$bar = ucfirst(strtolower($bar)); // Hello world!
?>
$upper = strtoupper(substr('katii', 0, 1)); //K
You should make your question a little clearer in future, though.

Is htmlspecialchars() safe enough?

The user input is like this
$user_input = htmlspecialchars($_GET['$user_input']);
According to PHP.net:
'&' (ampersand) becomes '&'
'"' (double quote) becomes '"' when ENT_NOQUOTES is not set.
"'" (single quote) becomes ''' (or &apos;) only when ENT_QUOTES is set.
'<' (less than) becomes '<'
'>' (greater than) becomes '>'
But what about $? For example the code is like this:
echo "Some cool text $user_input";
Now lets say user input is $secretCode so:$_GET['$user_input'] = "$secretCode";
Will the code then not echo the $secretCode?
Also what about this. Lets assume the code is like this:
$html = <<<EOF <head>.... EOF;
What if the input is $_GET['$user_input'] = "EOF;"; Won't this quit the string?
You're assuming a level interpretation that doesn't exist. If you write string literals like this:
$foo = 'bar';
$baz = "Hello $foo";
Then yes, $foo will be interpolated into the string. That is because it is explicitly written as a string literal in PHP source code.
On the other hand:
$foo = 'bar';
$baz = $_GET['var'];
Under no circumstances whatsoever will anything be interpolated here. Nor here:
$foo = <<<EOL
$_GET[var]
EOL;
$_GET['var'] can contain whatever it wants to, it is of no concern. PHP does not recursively evaluate all values over and over to see if there may be something that can be interpolated. There is no security issue here.
To provoke any of this recursive behaviour, you'd have to explicitly construct PHP source code as a string and then explicitly evaluate it:
$code = <<<EOL
$foo = 'bar';
echo "Hello $_GET[var]";
EOL;
// $code is now, say:
// $foo = 'bar';
// echo "Hello $foo";
eval($code);
Unless you do something like this (and please, never use eval), nothing will happen.
For embedding arbitrary text inside of HTML, htmlspecialchars is fine to escape characters which have a special meaning in HTML; yes, it's secure.
php will not parse variables inside variables itself, because the variable is not clearly written in your php code, php dont parse variables at this level. so with this in mind the following examples will fail and will output some text and $bar and not some text and test
$_GET['foo'] = '$bar';
$baz = $_GET['foo'];
$bar = 'test';
echo "some text and $baz";
// some text and $bar
Constant strings in your PHP code will be parsed like that, but strings that come from another source are not.
So in the line below, the variable $world will be expanded:
$var = "Hello $world";
In the line below, the exact value is used as it is read from (probably) a database. Even if the field 'example' world contain the text 'Hello $world', the variable $world would not be expanded.
$var = $row['example'];
This is normal PHP behaviour and is not related per se to htmlspecialchars.

Make string title case using ucfirst

I'm probably missing something really obvious.
While converting a bunch of string before inserting them in a array I noticed some string where different among each other because of first char being uppercase or not. I decided then to use ucfirst to make first character uppercase but it seems it doesn't work properly, I have had a look around on the web trying to figure out why this is happening but I had no luck.
$produtto = 'APPLE';
echo ucfirst($produtto);
//output: APPLE
If I use instead mb_convert_case
$produtto = 'APPLE';
echo mb_convert_case($produtto, MB_CASE_TITLE, "UTF-8");
//Output: Apple
ucfirst() only looks at the first character so you should convert to lowercase first.
Use this:
$produtto = 'APPLE';
echo ucfirst(strtolower($produtto));
//output: Apple
In the first case I assume you would first need to turn them lowercase with strtolower, and then use ucfirst on the string.
http://php.net/manual/en/function.mb-convert-case.php
MB_CASE_TITLE is not the same as ucfirst(). ucfirst is only interested in the first character. MB_CASE_TITLE is about the whole string and making it an initial capital string.
read the manual! APPLE = uppercase.. so ucfirst does nothing.
www.php.net/ucfirst
$foo = 'hello world!';
$foo = ucfirst($foo); // Hello world!
$bar = 'HELLO WORLD!';
$bar = ucfirst($bar); // HELLO WORLD!
$bar = ucfirst(strtolower($bar)); // Hello world!

Whats the difference between {$var} and $var?

I would like to know when and why should I use {$var}
echo "This is a test using {$var}";
and when (and why) should I use the simple form $var
echo "This is a test using $var";
You would use the latter when a) not accessing an object or array for the value, and b) no characters follow the variable name that could possibly be interpreted as part of it.
http://php.net/manual/en/language.variables.variable.php
In order to use variable variables with arrays, you have to resolve an
ambiguity problem. That is, if you
write $$a[1] then the parser needs to
know if you meant to use $a[1] as a
variable, or if you wanted $$a as the
variable and then the [1] index from
that variable. The syntax for
resolving this ambiguity is: ${$a[1]}
for the first case and ${$a}[1] for
the second.
The brackets allow you to remove ambiguity for the PHP parser in some special cases.
In your case, they are equivalent.
But consider this one:
$foobar = 'hello';
$foo = 'foo';
echo "${$foo . 'bar'}"; // hello
Without the brackets, you will not get the expected result:
echo "$$foo . 'bar'"; // $foo . 'bar'
For clarity purposes, I would however strongly advise against this syntax.
If you write
echo "This is a test using $vars"
You do not get content of $var in result text.
If you write
echo "This is a test using {$var}s";
Everything will be OK.
P.S. It works only with "" but not for ''.
The {} notation is also useful for embedding multi-dimensional arrays in strings.
e.g.
$array[1][2] = "square";
$text = "This $array[1][2] has two dimensions";
will be parsed as
$text = "This " . $array[1] . "[2] has two dimensions";
and you'll end up with the text
This Array[2] has two dimensions
But if you do
$text = "This {$array[1][2]} has two dimensions";
you end up with the expected
This square has two dimensions.

How do I replace custom "tags" in a string?

Given the following:
$foo = "Yo [user Cobb] I heard you like dreams so I put a dream in yo dream in yo dream so you can dream while you dream while you dream."
I'd like to do this:
$foo = bar($foo);
echo $foo;
And get something like this:
Yo Cobb I heard you like dreams so I put a dream in yo dream in yo dream so you can dream while you dream while you dream.
I'm unsure of how the bar function should work. I think this is doable with regular expressions but I personally find those hard to understand. Using the strpos function is another method but I wonder if there is a better solution.
Pseudocode is fine but actual code will be appreciated.
Edit:
These tags are not placeholders as the 2nd part is a variable value.
Edit:
All of the str_replace answers are incorrect as the tags contain variable content.
You could use preg_match_all to search the string for tags.
function bar($foo)
{
$count = preg_match_all("/\[(\w+?)\s(\w+?)\]/", $foo, $matches);
if($count > 0)
{
for($i = 0; $i < $count; $i++)
{
// $matches[0][$i] contains the entire matched string
// $matches[1][$i] contains the first portion (ex: user)
// $matches[2][$i] contains the second portion (ex: Cobb)
switch($matches[1][$i])
{
case 'user':
$replacement = tag_user($matches[2][$i]);
str_replace($matches[0][$i], $replacement, $foo);
break;
}
}
}
}
Now you can add more functionality by adding more cases to the switch.
As the tags contain content you want to parse and are not static to be replaced tags you’ll have to use regular expressions. (It’s the easiest way to go.)
preg_replace() is the regular expression function to replace text.
$pattern = '/\[user (\w+)\]/i';
$rpl = '${1}';
return preg_replace($pattern, $rpl, $foo);
This will match for a [user xy] tag where xy is a word (sequence of word-characters) of at least one character. As it is in parenthesis it is accessible with {1} in the replace-string. $foo is the string you want to parse. Returned is the parsed string with replaced tag. The i modifier on the pattern will make the matching case-insensitive. Remove it if you want it to be case-sensitive.
(The example you gave parses from [user Cobb] to a wikipedia url leonardo dicabrio, which is in no correspondence to neither user nor Cobb. So however you got there, you’ll have to do that (query a db? whatever). If it was just not careful enough providing example code; you probably wanted to point to a static url and add part of the tag content to it, which is what I did here.)
str_replace() is going to be your best option:
function bar($foo) {
$user = 'Cobb';
return str_replace('[user]', $user, $foo);
}
$foo = 'Yo [user] I heard you like dreams so I put a dream in yo dream in yo dream so you can dream while you dream while you dream.'
$foo = bar($foo);
print $foo; // Will print "Yo Cobb I heard you like dreams so I put a dream in yo dream in yo dream so you can dream while you dream while you dream."
What about str_replace?
function bar(foo)
return str_replace($arrayWithStringsToGetReplaced,
$arrayWithStringsToReplaceWith,
$foo)
If I understand the comments below
correctly.
This is obviously beyond me. Moving on... :)
Regular Expressions are the way to go. Hard yes, but the benefit gained from learning them far outweighs the effort needed to learn.
From php.net
<?php
$text = 'The price is PRICE ';
$lookFor = 'PRICE';
$replacement = '$100';
echo $replacement.'<br />';
//will display
//$100
echo str_replace($lookFor, $replacement, $text).'<br />';
//Will display
//The price is $100
?>

Categories