0

All I want to do is get the first word from a string, it does work, but how do I get rid of the comma as well, right now I'm getting name, I want it to to just display the name with no commas or characters after.

    <?php $pet_name = $pet->pet_name(); $arr = explode(' ',trim($pet_name));?>
    <h1><?= $arr[0] ?></h1>
user2677350
  • 338
  • 2
  • 13

3 Answers3

2

preg_split might be more helpful here than explode:

<?php 
    $pet_name = $pet->pet_name(); 
    $arr = preg_split('/[ ,]/', $pet_name, null, PREG_SPLIT_NO_EMPTY);
?>

This will treat any sequence of spaces and commas as delimiter when splitting up the name.

explode(' ', 'Smith, John'); // ['Smith,', 'John']
explode(' ', 'Smith,John'); // ['Smith,John']
preg_split('/[ ,]/', 'Smith, John', null, PREG_SPLIT_NO_EMPTY); // ['Smith', 'John']
preg_split('/[ ,]/', 'Smith,John', null, PREG_SPLIT_NO_EMPTY); // ['Smith', 'John']
Tgr
  • 27,442
  • 12
  • 81
  • 118
0
$name = str_replace(',','',$arr[0]);

str_replace is used to replace the comma with nothing

Ali
  • 3,479
  • 4
  • 16
  • 31
0

I see two ways of doing this.

First way. The way I suggest :

rtrim($arr[0], ',');

Second way. The problem with this is, if the last caracter is not a commas, it will also remove it :

substr($arr[0], 0, strlen($arr[0]) - 1);
David Bélanger
  • 7,400
  • 4
  • 37
  • 55
  • @Salim I know, that's why I added text to the description. However, if you are 120% sure it's always a commas at the end (like pre-created string or whatelse, it's faster. – David Bélanger Sep 06 '13 at 18:53
  • @Salim so what if unexpected shows up if there's no comma? the guy clearly says THERE IS a comma – Ali Sep 06 '13 at 18:55
  • Yep - Will be faster then regex and rtrim, I guarantee you. If you are 200% sure there's always a comma at the end, this is the way to go. – David Bélanger Sep 06 '13 at 18:57