Warning: Use of undefined constant - Bring PHP project to 8.2 - php

I have an old big project where many array are define without quotes.
An example is:
$a=$row["string1"];
$b=$row['string2'];
$c=$row[string3];
echo "Bye bye";
$var="I am $row['string4']!";
$var="I am $row[string5]!";
$row[string6];
$row[string7
];
$arr[]="I am $row[string8]!";
$arr[]=["message", "I am $row[string8]"];
if (true) {
echo "Hello [how are you]".
}
$myarr[string9]="bye";
I need a regular expression that matches arrays without quotes to include the quotes with the preg_replace() function.
I try with this regex /(?<=\[)([^'"].*[^'"])(?=\])/g but it doesn't just select arrays.
https://regex101.com/r/ZRM9Ie/1
If i use /(?<=\$row\[)([^'"].*[^'"])(?=\])/g work fine but if the array isn't named $row, it doesn't work
In my example only string3,string5,string6,string7,string8 are in scope and $row[string3] will be $row["string3"]
Thanks in advance!!

UPDATE:
I found this regular expression
/(?<arr>\$\w+\[)(\s)(?<var>[^"']+?)(\s)\]/g
You can use phpstorm for replacement with this patter of replace
${arr}"${var}"]
PhpStorm Example:
https://i.stack.imgur.com/AYRjK.png

Related

Regex to validate if string is a variable

I'm currently working on a small framework type of project. In this project a eval() is needed. This eval string is not user-submitted, but i would still like to validate that the string is a (contains a) variable.
The types of variable could be both normal variables, class properties and superglobal variables. I'm new to regex so I would appreciate any help.
Just to clarify: the string would be this as an example contain something like this '$_GET["something"]'.
You can use the following :
(\$[a-zA-Z_]\w*(\[(["'])\w+\3\])?|\$\{\w+\})
See DEMO
Note: It is better to use some libraries like this and this than using a regex solution. (From the discussions)
\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(?:\[["']\w+["']\])?
DEMO
ps.: (Extended) ASCII 228 is accepted in PHP
Reference: php variables

replace all smileys by enumeration in php

Is there any fast (regex-based?) method to replace all smileys in a text, each by an unique corresponding identifier? For example, the first occurrence of :) should be replaced by smiley1, the :)) by smiley2 and another occurrence of :) by smiley1 again? Furthermore, the identifyier should be the same using different text for input
Any potential combination of the typical symbols (<5 chars?) such as :;-()&%}{[]D<>30_o should be recognizable.
Can this be done without a generating a large array of all combinations? In case, how?
Are you looking for preg_replace_callback()? You can even use closures in php 5.3. I am not clear on what the objective is, so at this point this is the best I can provide, if you can clarify, then maybe I can see what I can come up with for sample code.
edit, here's an example from the PHP manual. Doesn't help in this case specifically, but if you just change the regex, the function and the string (basically everything, lol), then it will do the job:
<?php
echo preg_replace_callback('/-([a-z])/', function ($match) {
return strtoupper($match[1]);
}, 'hello-world');
// outputs helloWorld
?>
I don't understand why you can't do:
str_replace(":))","<img src=\"smiley1.jpg\">",$STRING)
str_replace(":)","<img src=\"smiley2.jpg\">",$STRING)
etc... seems to be the most simple solution and logical
Obviously, it cannot be done by using such a str_replace. How would you fetch a ":)))" or maybe a "-.-" which is also not present in your list? Enumerating all potential smileys is a hard task, resulting in n!/(n-k)! candidates. Here, in the example provided above n=18 and k=5...
Thus, I'm asking for a way to use a regex - but I don't how to replace each combination of chars which is intended to represent a smiley each time by the same text.
Idea: is it possible to use a callback function in combination with a hash?
Yeah, Tim! That is exactely what came into my mind when writing the last post. So the solution is
<?php
echo preg_replace_callback("/([\)\(\[\]<>#-\.:;*+{}]{2,9})/", function ($match) {
return " ".md5($match[1])." ";
}, ':::-) :-)) nope (yeah) cool:) }:)');
?>
Thanks!

PHP constant string square bracket indexing

I'm trying to get a constant string and index it as if it was an array of characters (square bracket syntax). When I try this code it fails on the last line.
define( 'CONSTANT_STRING','0123456789abcdef');
echo CONSTANT_STRING; // Works by itself :)
$string = CONSTANT_STRING;
echo $string[9]; // Also works by itself.
echo strlen(CONSTANT_STRING); // Also works by itself.
echo substr(CONSTANT_STRING, 9, 1); // Ok, yes this works, but not as clean.
echo CONSTANT_STRING[9]; // Fails as a syntax (parse) error.
I am using a constant string like this in a function. Since it could be called multiple times on one page it really should be a constant. What is the best option if there is no way to do this like I originally intended.
PHP Constants can only be scalar values, so the engine doesn't try to properly parse a constant that's used as something more than a scalar, like an array or an object.
This is a problem in your case because the brackets are used to point at an array index and can be used as a shortcut to grab a character at a specific location in the string.
You'll just have to do it the "hard" way and use substr().

Constants inside quotes are not printed?

This prints apple:
define("CONSTANT","apple");
echo CONSTANT;
But this doesn't:
echo "This is a constant: CONSTANT";
Why?
Because "constants inside quotes are not printed". The correct form is:
echo "This is a constant: " . CONSTANT;
The dot is the concatenation operator.
define('QUICK', 'slow');
define('FOX', 'fox');
$K = 'strval';
echo "The {$K(QUICK)} brown {$K(FOX)} jumps over the lazy dog's {$K(BACK)}.";
If you want to include references to variables inside of strings you need to use special syntax. This feature is called string interpolation and is included in most scripting languages.
This page describes the feature in PHP. It appears that constants are not replaced during string interpolation in PHP, so the only way to get the behavior you want is to use the concatenation that Artefacto suggested.
In fact, I just found another post saying as much:
AFAIK, with static variables, one has
the same 'problem' as with constants:
no interpolation possible, just use
temporary variables or concatenation.
Concatenation has been suggested as the only solution here, but that doesn't work when using syntax like:
define("MY_CONSTANT", "some information");
$html = <<< EOS
<p>Some html, **put MY_CONSTANT here**</p>
EOS;
Of course, the above just puts the text 'MY_CONSTANT' in $html.
Other options include:
define a temporary variable to hold the constant:
$myConst = MY_CONSTANT;
$html = <<< EOS
<p>Some html, {$myConst} </p>
EOS;
if there are many constants, you can get an array of them all and use that:
$constants = get_defined_constants();
$html = <<< EOS
<p>Some html, {$constants["MY_CONSTANT"]} </p>
EOS;
Of course, in such a trivially short example, there's no reason to use the <<< operator, but with a longer block of output the above two may be much clearer and easier to maintain than a bunch of string concatenation!
The question was already answered, but I'd like to provide a more generic insight on this.
In double quotes, PHP recognizes anything starting with a $ as a variable to be interpolated. Further more, it considers array and object access ([] and ->) but only up to a single level. E.g. "$foo->bar" interpolates $foo->bar and $foo->bar->baz does the same thing and treats ->baz as a string literally. Also, the quotes in [] must be ommited for string keys. E.g. "$foo[bar]" interpolates $foo['bar'] while "$foo['bar']" is a syntax error. AFAIK, that's it. To get more functionality, you need the "{$...}" syntax.
The $ here is actually a part of the syntax and it doesn't work without it. E.g. "{FOO}" will not interpolate a constant FOO, it's simply a syntax error. However, other than some strange syntactical restrictions, this construct is actually quite strong and may contain any valid PHP expression, as long as it starts with a $ and is an array access, object access, or a function call. (Maybe some other cases are permitted to. Please let me know, if anyone has a better understanding of this.) The most general solution to your problem would be to define something like the following function somewhere in your code base:
$id = function ($x) {
return $x;
}
It's simply the identity function - it returns whatever you give it. It must be defined as an anonymous function, so you can refer to it as $id with the $.
Now you can use this function to interpolate any PHP expression:
echo "{$id(CONSTANTS)}"
echo "{$id($some + $operators - $as . $well)}"
// etc...
Alternative for PHP versions < 5.3 where you can't use anonymous functoins:
class Util {
function id ($x) { return $x; }
}
$u = new Util;
echo "{$u->id(ANY + $expression . $here)}"
// or...
function id ($x) { return $x; };
$id = 'id';
echo "{$id(ANY + $expression . $here)}"
The native interpolation does not support constants. Still not up to PHP 8.2 (and maybe later on). An alternative to echo is to use printf() or sprintf() for getting the interpolation result as string.
const MY_CONSTANT = "foo";
printf("Hello %s bar!", MY_CONSTANT);

PHP: Access Array Value on the Fly

In php, I often need to map a variable using an array ... but I can not seem to be able to do this in a one liner. c.f. example:
// the following results in an error:
echo array('a','b','c')[$key];
// this works, using an unnecessary variable:
$variable = array('a','b','c');
echo $variable[$key];
This is a minor problem, but it keeps bugging every once in a while ... I don't like the fact, that I use a variable for nothing ;)
The technical answer is that the Grammar of the PHP language only allows subscript notation on the end of variable expressions and not expressions in general, which is how it works in most other languages. I've always viewed it as a deficiency in the language, because it is possible to have a grammar that resolves subscripts against any expression unambiguously. It could be the case, however, that they're using an inflexible parser generator or they simply don't want to break some sort of backwards compatibility.
Here are a couple more examples of invalid subscripts on valid expressions:
$x = array(1,2,3);
print ($x)[1]; //illegal, on a parenthetical expression, not a variable exp.
function ret($foo) { return $foo; }
echo ret($x)[1]; // illegal, on a call expression, not a variable exp.
This is called array dereferencing. It has been added in php 5.4.
http://www.php.net/releases/NEWS_5_4_0_alpha1.txt
update[2012-11-25]: as of PHP 5.5, dereferencing has been added to contants/strings as well as arrays
I wouldn't bother about that extra variable, really. If you want, though, you could also remove it from memory after you've used it:
$variable = array('a','b','c');
echo $variable[$key];
unset($variable);
Or, you could write a small function:
function indexonce(&$ar, $index) {
return $ar[$index];
}
and call this with:
$something = indexonce(array('a', 'b', 'c'), 2);
The array should be destroyed automatically now.
This might not be directly related.. But I came to this post finding solution to this specific problem.
I got a result from a function in the following form.
Array
(
[School] => Array
(
[parent_id] => 9ce8e78a-f4cc-ff64-8de0-4d9c1819a56a
)
)
what i wanted was the parent_id value "9ce8e78a-f4cc-ff64-8de0-4d9c1819a56a".
I used the function like this and got it.
array_pop( array_pop( the_function_which_returned_the_above_array() ) )
So, It was done in one line :)
Hope It would be helpful to somebody.
function doSomething()
{
return $somearray;
}
echo doSomething()->get(1)->getOtherPropertyIfThisIsAnObject();
actually, there is an elegant solution:) The following will assign the 3rd element of the array returned by myfunc to $myvar:
$myvar = array_shift(array_splice(myfunc(),2));
Or something like this, if you need the array value in a variable
$variable = array('a','b','c');
$variable = $variable[$key];
There are several oneliners you could come up with, using php array_* functions. But I assure you that doing so it is total redundant comparing what you want to achieve.
Example you can use something like following, but it is not an elegant solution and I'm not sure about the performance of this;
array_pop ( array_filter( array_returning_func(), function($key){ return $key=="array_index_you_want"? TRUE:FALSE; },ARRAY_FILTER_USE_KEY ) );
if you are using a php framework and you are stuck with an older version of php, most frameworks has helping libraries.
example: Codeigniter array helpers
though the fact that dereferencing has been added in PHP >=5.4 you could have done it in one line using ternary operator:
echo $var=($var=array(0,1,2,3))?$var[3]:false;
this way you don't keep the array only the variable. and you don't need extra functions to do it...If this line is used in a function it will automatically be destroyed at the end but you can also destroyed it yourself as said with unset later in the code if it is not used in a function.

Categories