PHPRO.ORG

PHP Switch Using Regular Expression Regex

PHP Switch Using Regular Expression Regex

The PHP switch function is a useful tool as an alternative to long if/elseif/else statements. In this example, the switch function is used in conjuction with a regular expression to detirmine the program flow.

For more amazingness on the PHP switch function see http://phpswitch.com


<?php

    
/**
    *
    * Greeting based on name
    *
    * @access    public
    * @param    string    $string
    * @return    string
    *
    */
    
function greeting$string )
    {
        switch( 
$string )
        {
            
// check if the string begins with John
            
case ( preg_match'/John.*/'$string ) ? true false ):
            
$ret "Welcome John";
            break;

            
// check if the string begins with Kev
            
case ( preg_match'/Kev.*/'$string ) ? true false ):
            
$ret "G'day Kev";
            break;
    
            
// check if the string begins with Per
            
case ( preg_match'/Jome.*/'$string ) ? true false ):
            
$ret "Hej da, Per";
            break;

            
// if there is no match, throw exception with error message
            
default: throw new Exception"None shall pass" );
        }

        
// return the value
        
return $ret;
    }

Usage


<?php
    
// a string to test
    
$string 'Kev is in the house';

    
// lets look for a greeting message
    
try
    {
        echo 
greeting$string );
    }
    catch( 
Exception $e )
    {
        echo 
$e->getMessage();
    }
?>