1

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);
3
  • 4
    What is it you want to do? There is no $2 in that regex by the way... Commented Jul 17, 2009 at 11:58
  • In some regexes, missing references are just treated as blank, so the $2 may effectively just remove the matches. Commented Jul 17, 2009 at 12:44
  • Yes, it does, but so does ''. Commented Jul 17, 2009 at 13:13

2 Answers 2

1

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']));
Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.