1

Is there any way to use a regex expression to create a string, instead of just finding if a match exists?

I have a function to create a random string of characters:

public function getRandomString($length=8) {

  $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  $string = '';

  for ($p = 0; $p < $length; $p++) {
    $string .= $characters[mt_rand(0, strlen($characters)-1)];
  }

  return $string;

} // End

I was wondering if there was any way to use a regex expression like /[a-zA-Z0-9] instead of typing out all the characters...?

2
  • You will certainly look for range(). Commented Dec 29, 2016 at 18:56
  • Not a regex, but have a look for range()`. Commented Dec 29, 2016 at 18:56

1 Answer 1

1

Have a look at range():

$letters = range('0', 'Z');
Sign up to request clarification or add additional context in comments.

1 Comment

When I replace the above function $characters string with your range example, it's not working because range creates an array.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.