Juliver Galleto
Juliver Galleto

Reputation: 9037

detect if string contains only comma, then remove the comma php

First I have a dynamic string like this

,

and sometimes like this

firstname,

and sometimes like this too

, lastname

how can I detect like if string contains only comma then make the string empty (remove the comma) else if string contains firstname and comma (no lastname, see format below)

firstname,

then remove the comma inside the string and keep the firstname else if the string contains comma and lastname then remove the comma as well and keep the lastname inside the string.

any ideas, help, clues, suggestions, recommendations to achieve that please?

Upvotes: 0

Views: 1679

Answers (3)

Shakil Ahamed
Shakil Ahamed

Reputation: 39

You may try this

  <?php     

      $name = 'Firstname,';   // If you give value "," you will get blank

      $filename_withou_comma = explode (',',$name);
      echo $filename_withou_comma[0];
      echo $filename_withou_comma[1];

      ?>

Upvotes: 1

Chris Evans
Chris Evans

Reputation: 1265

You can replace all occurrences of a string from within a string with str_replace, which will work even if the comma is in the middle of the string.

//Here we are replacing all occurrences of "," with "" inside $string
$string = str_replace(",", "", $string);

If you just want to remove the commas from the left / right, then trim() is the way to go, as follows:

$string = trim($string, ",");

Sources:

http://php.net/manual/en/function.str-replace.php

http://php.net/manual/en/function.trim.php

Hope I was helpful!

Upvotes: 2

Roadirsh
Roadirsh

Reputation: 572

If your comma is only at the beginning and at the end of your string you could do that:

$firstname = rtrim('firstname', ',');
$lastname = ltrim(', lastname', ', ');

Check out ltrim and rtrim

Upvotes: 2

Related Questions