A little help with str replace needed

Discussion in 'PHP' started by edual200, May 16, 2008.

  1. #1
    My script gets $state from the search parameter, i would like it to spell out the word for every state, if possible in 1 line of code so that i can just put $stateword as the replacement regardless of the state.

    This works for 1 state, i just dont know how to add more states to it

    $stateword = str_replace("fl", "Florida", "$state");

    Thanks
     
    edual200, May 16, 2008 IP
  2. nVaux

    nVaux Peon

    Messages:
    54
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    $stateword = str_replace('fl', 'Florida', $state);
    $stateword = str_replace('ca', 'California', $stateword);
    $stateword = str_replace('or', 'Oregon', $stateword);
    PHP:
    You don't need to enclose a variable in double quotes, and for your other quotes use single quotes when you just have plain text, PHP executes code faster that way.
    Althought str_replace does the job, you will be using up more processing than needed, might I suggest using a switch function instead?
    function get_state($state)
    {
    	switch($state)
    	{
    		case 'ca':
    			return 'California';
    			break;
    		case 'fl':
    			return 'Florida';
    			break;
    		default:
    			return false;
    			break;
    	}
    }
    PHP:
    use like this:

    $state = get_state($state);
    PHP:
    Happy coding!
     
    nVaux, May 16, 2008 IP
  3. geforce

    geforce Active Member

    Messages:
    173
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    78
    #3
    You could also use an array and even put it in function like so:

    Function
    
    
    <?php
    
    function get_state($state)    {
    
       $state_names = array('fl' => 'Florida',
                              'ca' => 'California'
                                     );
    
      $state_name = $state_names[ $state ];
    
      return $state_name;
    
    }
    
    ?>
    
    
    PHP:
    You could simply keep adding to that array as it is structured then call the function:

    
    
    <?php
    
       $state = get_state('fl');
    
    ?>
    
    
    PHP:
    To me the above way is a lot easier and takes less processing as you are only consulting an array.
     
    geforce, May 17, 2008 IP