Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expressions: RegEx for determining valid PHP class property names?

Tags:

regex

oop

php

I am using PHP's magic __set and __get methods to access a private array in a class. Use of the class can include "setting" new properties as well as using existing ones. I want to make sure the property names created or requested (i.e. $myObj->FakeProperty) are valid according to the following rules:

  1. Property names must begin with either a letter or underscore [A-z_]
  2. If it begins with an underscore, it must be followed by a letter
  3. So long as the first two rules are met, the name may contain any of [A-z0-9_]

My current RegEx isn't doing the trick; with my test values, _12 always falls through the cracks.

Test Fields:

albert12
12Albert
_12
_Albert12
_12Albert
_____a_1

RegEx:

^(?=_*[A-z]+)[A-z0-9_]+$
like image 603
Brian Lacy Avatar asked Dec 02 '25 11:12

Brian Lacy


1 Answers

according to docs, the following would match any valid php identifier

/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/
like image 83
user187291 Avatar answered Dec 05 '25 00:12

user187291



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!