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>
1

3 Answers 3

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']
Sign up to request clarification or add additional context in comments.

Comments

0
$name = str_replace(',','',$arr[0]);

str_replace is used to replace the comma with nothing

Comments

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);

3 Comments

@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.
@Salim so what if unexpected shows up if there's no comma? the guy clearly says THERE IS a comma
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.