PHP: What do the curly braces in $variable{0} do? - php

I was going through a codebase and came across a line I had a question about. It's something I haven't seen before and I was wondering if someone could explain it for me. Here's the code:
$variableName = $array[1];
$variableName{0} = strtolower($variableName{0});
$this->property = $variableName;
What are the curly braces being used for? I've used curly braces to define variables as variable names before, but is this the same thing? I can't seem to find any resources online that explain it, but I'm not sure if I'm searching for the right thing.

access the single byte with that index {0} => first char (in non-utf8 string)
you could simply test it with:
$var='hello';
echo $var{0};

It's setting the first character of the string to lower case. It's a string shortcut operator, functioning the same as this:
<?php
$variableName = strtolower(substr($variableName, 0, 1)) . substr($variableName, 1)

Curly braces {} work the same as square brackets [], for array or string indexing. I'm guessing it is borrowed from perl, in which the square brackets are used for arrays and braces are used for hashes. But in PHP arrays and hashes are the same thing.

Related

Array and string offset access syntax with curly braces is no longer supported [duplicate]

In PHP you can access characters of strings in a few different ways, one of which is substr(). You can also access the Nth character in a string with curly or square braces, like so:
$string = 'hello';
echo $string{0}; // h
echo $string[0]; // h
My question is, is there a benefit of one over the other? What's the difference between {} and []?
Thanks.
use $string[0], the other method (braces) has been removed in PHP 8.0.
For strings:
Accessing characters within string literals using the {} syntax has been deprecated in PHP 7.4. This has been removed in PHP 8.0.
And for arrays:
Prior to PHP 8.0.0, square brackets and curly braces could be used interchangeably for accessing array elements (e.g. $array[42] and $array{42} would both do the same thing in the example above). The curly brace syntax was deprecated as of PHP 7.4.0 and no longer supported as of PHP 8.0.0.
There is no difference. Owen's answer is outdated, the latest version of PHP Manual no longer states that it is deprecated §:
Characters within strings may be accessed and modified by specifying
the zero-based offset of the desired character after the string using
square array brackets, as in $str[42]. Think of a string as an array
of characters for this purpose. [...]
Note: Strings may also be accessed using braces, as in $str{42}, for
the same purpose.
However it seems that more people/projects use [], and that many people don't even know {} is possible. If you need to share your code publicly or with people who don't know the curly brace syntax, it may be beneficial to use [].
UPDATED : accessing string characters with {} is deprecated, use [] instead.
Yes, there's no difference. This language quirk has some history...
Originally, the curly brace syntax was intended to replace the square bracket syntax which was going to be deprecated:
http://web.archive.org/web/20010614144731/http://www.php.net/manual/en/language.types.string.php#language.types.string.substr.
Later that policy was reversed, and the square brackets syntax was preferred instead:
http://web.archive.org/web/20060702080821/http://php.net/manual/en/language.types.string.php#language.types.string.substr
and even later, the curly braces one was going to be deprecated:
http://web.archive.org/web/20080612153808/http://www.php.net/manual/en/language.types.string.php#language.types.string.substr
As of this writing, it seems that the deprecation has been withdrawn as well and they are just considered two alternative syntaxes:
http://web.archive.org/web/20160607224929/http://php.net/manual/en/language.types.string.php#language.types.string.substr
Curly brace access was deprecated in PHP 7.4
Array and string offset access using curly braces ¶
The array and string offset access syntax using curly braces is
deprecated. Use $var[$idx] instead of $var{$idx}.
PHP 7.4 Deprecated Features, PHP Core

PHP parser: braces around variables

I was wondering, how is the semantics of braces exactly defined
inside PHP? For instance, suppose we have defined:
$a = "foo";
then what are the differences among:
echo "${a}";
echo "{$a}";
that is, are there any circumstances where the placement of the
dollar sign outside the braces as opposed to within braces makes
a difference or is the result always the same (with braces used
to group just about anything)?
There are a lot of possibilities for braces (such as omitting them), and things get even more complicated when dealing with objects or arrays.
I prefer interpolation to concatenation, and I prefer to omit braces when not necessary. Sometimes, they are.
You cannot use object operators with ${} syntax. You must use {$...} when calling methods, or chaining operators (if you have only one operator such as to get a member, the braces may be omitted).
The ${} syntax can be used for variable variables:
$y = 'x';
$x = 'hello';
echo "${$y}"; //hello
The $$ syntax does not interpolate in a string, making ${} necessary for interpolation. You can also use strings (${'y'}) and even concatenate within a ${} block. However, variable variables can probably be considered a bad thing.
For arrays, either will work ${foo['bar']} vs. {$foo['bar']}. I prefer just $foo[bar] (for interpolation only -- outside of a string bar will be treated as a constant in that context).
The brackets delimit where the variable name ends; this example should speak for itself.
$a = "hi!"
echo "$afoo"; //$afoo is undefined
echo "${a}foo"; //hi!foo
echo "{$a}foo"; //hi!foo
Also, this should spit out a warning; you should use
${'a'}
Otherwise it will attempt to assume a is a constant.
Also you can use braces to get Char in the position $i of string $text:
$i=2;
$text="safi";
echo $text{$i}; // f

I just need one line of Regex code edited

the following code works but how can it be edited to only detect the first curly brace after an end parenthesis?
'/\{(([^{}]*|(?R))*)\}/'
Example:
if (1==1)
{
echo "testing {$username}";
}
The problem is that it detects ALL curly brackets, even the one surrounding the $username variable. So I think a solution would be to detect is there is a ) before the first curly bracket. I tried about 20 different things myself but cannot get it to work. How can it be edited to only detect ) { Oh and please add code if there are spaces and tabs involved inbetween the first curly bracket and end parenthesis if that matters. Thanks.
You can use:
\)\s*\{
as part of your pattern to detect simple cases like your example. Note that you can't use a positive lookbehind of variable length though, so you can't alter it to (?<=)\s*){
My pattern will still pick up code that is commented out though, and won't detect code that has a comment between the ) and the {. You wouldn't want to use a regex to try to detect such cases.

Matching text between braces in PHP

In direct follow-up to this previous question, how can I pull the text (and the braces if possible) out as a match using PHP?
Specifically, I am writing a Wordpress plugin and am looking to reformat all text between two curly braces (a quasi wiki-marking).
I've followed the steps outlined in another previous question I asked, and have the matching part working - it's the match I need help with.
Example:
This is some {{text}} and I want to reformat the items inside the curly braces
Desired output:
This is some *Text fancified* and I want to reformat the items inside the curly braces
What I have (that is not working):
$content = preg_replace('#\b\{\{`.+`\}\}\b#', "<strong>$0</strong>", $content);
If matching including the braces is too difficult, I can match using the braces as offsets, and then remove the 'offending' braces afterwards, too, using a more simple text-match function.
$content = preg_replace('/{([^{}]*)}/', "<strong>$1</strong>", $content);
You need to form a match group using ( round braces ).
preg_replace('#\{\{(.+?)\}\}#', "<strong>$1</strong>",
Whatever (.+?) matches then can be used as $1 in the replacement string. This way you have the enclosing {{ and }} already out of the way. Also \b was redundant.

PHP: Find and exctract into an array all instances of specific text in a string

I have a string that contains several "placeholders" in it, and each placeholder is marked with this syntax: {value}.
I want to be able to pull out each placeholder within the string and load them into an array.
For example, if I had this string here... "this is a {test} string, to demonstrate my {objective}."
I would want the end result to be an array that contained two values, "test" and "objective".
I poked around with preg_split but couldn't quite wrap my head around it. Any ideas on how to make this happen?
Thanks!
You can try the following to get what you need:
$placeHolders = array();
if(preg_match_all('/\{([^{}}]+)\}/', $haystack, $matches)) {
$placeHolders = $matches[1];
}
Since you didn't specifically state what would be allowed in a place holder, I kept the regular expression quite generic. Basically, a placeholder would be anything inside curly braces (except for curly braces themselves).
You might want to restrict more, such as alphanumeric characters only. In this case try:
'/\{([a-zA-Z0-9]+)\}/'
Edit: a resource for regular expressions: http://www.regular-expressions.info/reference.html
I think you can use this
preg_match_all('/\{([^\}]+)\}/i', $your_string, $match);
all the placeholders in $match[1];
Read more about that function at http://php.net/manual/en/function.preg-match-all.php

Categories