Is there a way to optimize the following PHP code so that I can only use preg_replace and not preg_replace+substr?
$type = substr( preg_replace('/([^a-z])/', '$2', strtolower($_GET["type"])) , 0, 3);
Is there a way to optimize the following PHP code so that I can only use preg_replace and not preg_replace+substr?
$type = substr( preg_replace('/([^a-z])/', '$2', strtolower($_GET["type"])) , 0, 3);
As people noted in comments, your code sample is kinda dysfunctional, but if I understand what you want to do correctly (retrieve the first three lowercase alphabetic characters), then this should do it:
$type = preg_replace('/.*?([a-z])(?:.*?([a-z]))?(?:.*?([a-z]))?.*/', '$1$2$3', strtolower($_GET['type']));
To be honest, I would keep it simple and just alert the user if they entered an invalid string:
$type = $_GET['type'];
if (!preg_match('/^[a-z]{0,3}$/', $type)) {
// Handle error properly here.
die('Type argument must be a string of 0-3 lower case letters (a-z)');
}
If you really want to fix the input, then your original solution was fine, it could just be cleaned up a little:
$type = substr(preg_replace('/[^a-z]+/', '', strtolower($_GET['type'])), 0, 3);