3

Just started coding PHP, could someone point me to the right direction? I've got:

$text = Barcelona, Catalunya, Spain

I want to get only the first and last word which should be

OUTPUT: Barcelona, Spain

I tried this, but it gives me the 2 last words:

$text = explode(",", $text);
$size = array_slice($text, -2, 2);
$text = implode(",", $size);

OUTPUT: Catalunya, Spain

Could someone help please?

3
  • 2
    Take a look at array_pop and array_shift. They return first and last elements from a given array. Commented Nov 6, 2014 at 9:44
  • $text[0] for first and end($text) for last element or reset($text) for first element Commented Nov 6, 2014 at 9:45
  • People have replied so promptly, accept the answer that most suits you, but accept...To help others in future @ryan Commented Nov 6, 2014 at 11:41

7 Answers 7

2

Try this hope it will help you:

$text = "Barcelona, Catalunya, Spain";
$array = explode(",",$text);
$first_word = $array[0];
$last_word  = $array[count($array)-1];

echo $first_word. ', '.$last_word; 

Output:

Barcelona,  Spain
Sign up to request clarification or add additional context in comments.

Comments

0

Use current() for first element and end() for last element

$text = "Barcelona, Catalunya, Spain";
$exp = explode(", ", $text);

$string = current($exp) . ", " . end($exp);

DEMO

Comments

0

If you want to get the first and last x elements, you can use array_slice() but as you want the gap, simply array_combine() two slices like this

function createCenteredGap($gapLength, $text) {
    $length = (strlen($text) - $gapLength) / 2;
    $gapLength = 1;
    return array_merge(
        array_slice($text, 0, $length),
        array_slice($text, $length+$gapLength, $length)
    );
}

This will do the trick when called like createCenteredGap(1, $text) as you can see in this demo

1 Comment

@ryan will also work for larger lists ad gaps, but I would suggest that you check before the function if the explode worked as expected
0
<?php
   $array = array(Barcelona, Catalunya, Spain);
   $first = reset($array);
   $last = end($array);

   var_dump($first, $last);
?>

Comments

0

Try to use this very simple regexp

preg_match('/^(.[^,]*)\s*,.*,\s*(.*)$/', $text, $match);
$first = $match[1];
$last = $match[2];

If you are sure that elements are only words without digits and other symbols you can modify this regexp

Comments

0

$text now has the array of values so

first element:

$text[0]

or

reset($text)

last element:

end($text)

Comments

0

Don't split your string at all. Use preg_replace() to capture all consecutive repetitions of a comma followed by non-comma characters and replace the lot with the last repetition. Demo

echo preg_replace('#(,[^,]+)+#', '$1', $text);
// Barcelona, Spain

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.