views:

65

answers:

2

what is a quick way to filter a string to work as a function name?

note: I'm thinking something like filter_var().

+1  A: 

From the manual:

As a regular expression, it would be expressed thus: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

So, something like this, maybe?

function can_be_function($var) {
  return preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $var);
}
Emil Vikström
Emil, it looks like I misunderstood the question. Thanks for providing this.
macek
can this be made into a preg_replace so that the variable gets turned INTO a name that can be called as a function?
YuriKolovsky
+2  A: 

You might be looking for

  • is_callable — Verify that the contents of a variable can be called as a function

Verify that the contents of a variable can be called as a function. This can check that a simple variable contains the name of a valid function, or that an array contains a properly encoded object and function name.

If you just want to make sure the supplied value is valid syntax for a function name, you can set the second argument $syntax_only to TRUE:

syntax_only: If set to TRUE the function only verifies that name might be a function or method. It will only reject simple variables that are not strings, or an array that does not have a valid structure to be used as a callback. The valid ones are supposed to have only 2 entries, the first of which is an object or a string, and the second a string.

Gordon
in php first you make your own function to do something, and then you find out that php had this function built in all along!
YuriKolovsky
is there a function like is_callable that turns a dirty name into a valid one?
YuriKolovsky