Regex to validate if string is a variable - php

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

Related

Javascript (Node.js) in PHP

Is there any project like PHP.js but in vice direction to provide PHP implementation of JS classes and functions? In particular Date, RegEx, String classes?
I found this class for String but I am looking for a more complete collection.
My consern is not about using or not using such thing, I just need such thing.
Today I found jsphp. It seems promising.
JavaScript for PHP (jsphp) is a pseudo-implementation of the ECMA 262
standard (JavaScript 8.5.1) for PHP 5.3+. It allows you to write code
in PHP as if it were JavaScript, using the standard API and the
dynamic attributes available in the language, such as prototype
inheritence and chaining, first-class functions, and other
object-orientated features. It includes JSBoolean, JSNumber, JSString,
JSObject, JSArray, JSFunction, JSRegExp, JSDate, JSError and JSMath,
as well as the global helper functions, such as parseInt or isNaN.
The syntax in jsphp is very similar to a native implementation, although adapted to the syntax of PHP. For example, the variables are
prepended by a "$", the Object access opertaor is "->", and Strings
are concatenated using a ".".
$myString = new JSString( 'Hello World' );
$myString = $myString->split( '' )->reverse()->join( '' );
print( 'Reversed: ' . $myString ); // dlroW olleH
There is not - and there can not be - somehting like you ask for.
Javascript has a special syntax for regular expressions, something PHP could not take.
Similar how "object" methods in javascript are invoked. And the scope of variables is different. So this would not work.
Instead use the PHP functions. If they are not complete or useable enough for you, wrap them into objects so you can create an interface you like. Or use one of the many libraries that are available.

str_replace: Replace string with a function

Just a simple question. I have a contact form stored in a function because it's just easier to call it on the pages I want it to have.
Now to extend usability, I want to search for {contactform} using str_replace.
Example:
function contactform(){
// bunch of inputs
}
$wysiwyg = str_replace('{contactform}', contactform(), $wysiwyg);
So basically, if {contactform} is found. Replace it with the output of contactform.
Now I know that I can run the function before the replace and store its output in a variable, and then replace it with that same variable. But I'm interested to know if there is a better method than the one I have in mind.
Thanks
To answer your question, you could use PCRE and preg_replace_callback and then either modify your contactform() function or create a wrapper that accepts the matches.
I think your idea of running the function once and storing it in a variable makes more sense though.
Your method is fine, I would set it as a $var if you are planning to use the contents of contactform() more than once.
It might pay to use http://php.net/strpos to check if {contact_form} exists before running the str_replace function.
You could try both ways, and if your server support it, benchmark:
<?php echo 'Memory Usage: '. (!function_exists('memory_get_usage') ? '0' : round(memory_get_usage()/1024/1024, 2)) .'MB'; ?>
you may want to have a look at php's call_user_func() more information here http://php.net/call_user_func
$wysiwyg = 'Some string and {contactform}';
$find = '{contactform}';
strpos($wysiwyg, $find) ? call_user_func($find) : '';
Yes, there is: Write one yourself. (Unless there already is one, which is always hard to be sure in PHP; see my next point.)
Ah, there it is: preg_replace_callback(). Of course, it's one of the three regex libraries and as such, does not do simple string manipulation.
Anyway, my point is: Do not follow PHP's [non-]design guidelines. Write your own multibyte-safe string substitution function with a callback, and do not use call_user_func().

Is it possible to include PHP code that is in memory?

Say I have a variable containing PHP code, can I include its content as if it was a normal PHP file ?
For example, the PHP code could be a class declaration.
You don't have a variable containing php code. You have a string.
You can execute a string as php with the evil eval function, but puppies AND kittens will die!
eval($your_variable);
Be aware about security holes!This is very dangerous and should NOT be based on user's input !
You could use eval to evaluate any code that you have in your string, however it is evil. What exactly are you trying to do?

Do you have any personal visual clue in your code for other user and not the compiler?

i use certain suffix in my variable name, a combination of an underscore and a property. such as :
$variable_html = variable that will be parse in html code.
$variable_str = string variable
$variable_int = integer variable
$variable_flo = float variable.
Do you have other visual clues? Maybe something you write for variable, function name, class strucure, or other stuff that helps others to read and not only for compiler ?
You're describing Hungarian Notation: Do people use the Hungarian Naming Conventions in the real world?
There's lots of discussion on Stack Overflow about people's feelings on the topic.
It nearly is Hungarian Notation, but when you use Hungarian Notation it is more common to use a prefix instead of a suffix.

PHP: What does __('Some text') do?

Reading about Kohana templates and saw something I've never seen before:
$this->template->title = __('Welcome To Acme Widgets');
What does __('Text') mean? What is it? What does it do?
In Kohana (version 3) the function is defined in system/base.php and is a convenience function to aid (as the other answers have mentioned) internationalization. You provide a string (with, optionally, some placeholders to substitute values into the finished text) which is then interpreted and, if required, a translation is returned.
Contrary to assumptions in other answers, this does not use gettext.
A very basic example would be (this particular string is already translated into English, Spanish and French in Kohana):
// 1. In your bootstrap.php somewhere below the Kohana::init line
I18n::lang('fr');
// 2. In a view
echo __("Hello, world!"); // Bonjour, monde!
The double '__' is used for Localization in CakePHP (and possible other frameworks)
http://book.cakephp.org/view/163/Localization-in-CakePHP
It means someone created a function named __ (That's two underscores next to one another.)
My guess is it defined somewhere in the Kohana documentation.
It's string gettext ( string $message ): http://php.net/manual/en/function.gettext.php
Returns a translated string if one is
found in the translation table, or the
submitted message if not found.
The __() is just an alias for it. So __("some text") is equivalent to gettext("some text")
edit: Actually if it's two underscores than it isn't gettext(). The alias for gettext() is one underscore.
Second edit: It looks like __() might be another alias for gettext(). With a slightly different meaning from _(). See here: http://groups.google.com/group/cake-php/browse_thread/thread/9f501e31a4d4130d?pli=1
Third and final edit: Here's an article explaining it in more detail. Looks like it isn't a built in function, but rather something that is commonly added in a lot of frameworks. It is essentially an alias of gettext - it performs the same function. However, it isn't a direct alias (I don't think). It is implemented in and is specific to the framework. It searches for and returns a localization or translation of the string it is given. For more, see this blog post: http://www.eatmybusiness.com/food/2007/04/13/what-on-earth-does-a-double-underscore-then-parenthesis-mean-in-php-__/7/
// Display a translated message
echo __('Hello, world');
// With parameter replacement
echo __('Hello, :user', array(':user' => $username));
See http://kohanaframework.org/3.2/guide/api/I18n for details.

Categories