<?php
function isPhpKeyword($testString) {
// First check it's actually a word and not an expression/number/empty string
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;
}
var_dump(
isPhpKeyword('if'),
isPhpKeyword('flibble'),
isPhpKeyword('while')
);
- Output for 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.26, 8.4.1 - 8.4.13
- bool(true)
bool(false)
bool(true)
preferences:
131.02 ms | 407 KiB | 5 Q