1. 2015

    Problem Solving: Reverse words in a sentence

    Posted By

    Write a solution that takes in a sentence and reverses the words in a sentence while keeping the words in their same relative order/position. So a sentence like “check out this sentence” will now become “kcehc tuo siht ecnetnes”.

    Note: This solution takes into account punctuation marks.

    	function solution($W) {
    		$W_array = explode(" ", $W);
    		$result = array();
    		$counter = 0;
    		$reserved_chars = array('.', ',', '?', '!', ':', ';');
    		foreach($W_array as $W_item) {
    			$W_length = strlen($W_item);
    	       		$last_item = substr($W_item, $W_length-1, 1);
    		   	$result[$counter] = (in_array($last_item, $reserved_chars)) ? strrev(substr($W_item, 0, $W_length-1)) . $last_item : strrev($W_item);
    		return implode(" ", $result);

  2. About Emeka Echeruo

    Emeka Echeruo

    I love sports, football which I refuse to call soccer, and the outdoor especially walks in park. Software development is my passion, there is a beauty in creating something out of nothing but algebra that ends up becomes a part of a persons daily life. I love kids, dogs, nightlife and art because it finds you and moves you emotionally!

  3. Leave a Reply

    Your email address will not be published. Required fields are marked *

    This site uses Akismet to reduce spam. Learn how your comment data is processed.