Corona SDK and other Game Development Tutorials
@gamebuilding

Using Regular Expressions

Below are some samples of how to use regular expressions with php.

 Finding a Number in a String

Here’s how you would find a number in a string with php, but will stop on the first match. Of course, make sure to wrap your code with the php tags.

$pass = 'mypassword123';

if( preg_match('/\d/', $pass) ) {
 echo 'match found!';
 } else {
 echo 'match not found!';
 }

If you want to look at the entire string, you’ll need to use preg_match_all. This will return the results in an array. Here’s how.

$pass = 'mypassword123';

if( preg_match_all('/\d/', $pass) ) {
 echo 'match found!';
 } else {
 echo 'match not found!';
 }

Split a String with Regular Expressions

If you are looking to split a string based on certain criteria, you can use php’s preg_split function. By passing in a regular expression into the first parameter and the string to be split in the second parameter, you can easily split strings and get an array. Here’s how.

$mystring = 'First 2 Second';

$newstring = preg_split('/\d/', $mystring);
print_r($newstring);

What if you wanted to split a string based on two or more characters? That’s where the pipe command comes into play. The pipe command in regular expressions represents the ‘or’ option. So, you could pass in ‘/\d|;/’ into the first argument of the preg_split function to split the string on any numbers or semi-colons. Here’s how.

$mystring = 'First 2 Second ; Third';

$newstring = preg_split('/\d|;/', $mystring);
print_r($newstring);

Split a string based on the domain name

Every once in awhile, you might need just the prefix and suffix of an email address. You can use the look ahead command with regular expressions to single out the email address. If you have an email address that is dan@myemail.com and you just need the prefix – dan – and the suffix – .com – you can use the following php code.

$myemail = 'dan@myemail.com';

$domainname = preg_split('/@.+(?=\.[a-z]{2,4})/', $myemail);

Leave a Reply