I'm looking at this: https://www.php.net/manual/en/reserved.php I've made numerous search queries for things like: "php determine if string is reserved keyword".
I find nothing, and I'm starting to seriously sweat. Please don't tell me I'm going to have to code a complicated script to regularly scrape the PHP manual for all these various kinds of reserved keywords and build my own database!
Please let there be a nice, simple function to simply check:
var_dump(is_reserved_php_keyword('if'));
And it gives a true/false.
I went a different way to Andrew and instead went for having PHP figure it out rather than hard coding the list.
function isPhpKeyword($testString) {
// First check it's actually a word and not an expression/number
if (!preg_match('/^[a-z]+$/i', $testString)) {
return false;
}
$tokenised = token_get_all('<?php ' . $testString . '; ?>');
// tokenised[0] = opening PHP tag, tokenised[1] = our test string
return reset($tokenised[1]) !== T_STRING;
}
https://3v4l.org/WA6dr
This has a few advantages:
It doesn't need the list to be maintained as PHP's own parser says what's valid or not.
It's a lot simpler to understand.
Unfortunately, I'm not aware of any built-in function for what you describe. But based on the RegEx pattern you can find among the contributed notes on PHP.net, you can test it like this:
$reserved_pattern = "/\b((a(bstract|nd|rray|s))|(c(a(llable|se|tch)|l(ass|one)|on(st|tinue)))|(d(e(clare|fault)|ie|o))|(e(cho|lse(if)?|mpty|nd(declare|for(each)|if|switch|while)|val|x(it|tends)))|(f(inal|or(each)?|unction))|(g(lobal|oto))|(i(f|mplements|n(clude(_once)?|st(anceof|eadof)|terface)|sset))|(n(amespace|ew))|(p(r(i(nt|vate)|otected)|ublic))|(re(quire(_once)?|turn))|(s(tatic|witch))|(t(hrow|r(ait|y)))|(u(nset|se))|(__halt_compiler|break|list|(x)?or|var|while))\b/";
if(!preg_match($reserved_pattern, $myString)) {
// It is not reserved!
};
It may not be the most elegant-looking piece of PHP code out there, but it gets the job done.
UPDATE: See online demo of function here: https://3v4l.org/CdIjt
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With