检测字符串是否只包含逗号,然后删除逗号php


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

首先我有一个像这样的动态字符串

有时像这个

名字,

有时也像这样

,姓氏

我如何检测字符串是否只包含逗号,然后使字符串为空(删除逗号),否则如果字符串包含名字和逗号(没有姓氏,请参阅下面的格式)

名字,

然后删除字符串中的逗号并保留姓氏。否则,如果字符串包含逗号和姓氏,则也删除逗号并保留字符串中的姓氏。

有什么想法、帮助、线索、建议、建议可以实现吗?

您可以将字符串中出现的所有字符串替换为str_replace,即使逗号位于字符串中间,这也会起作用。

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

如果你只想删除左/右的逗号,那么trim()是一种方法,如下所示:

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

来源:

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

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

希望我能帮上忙!

如果逗号只在字符串的开头和末尾,则可以这样做:

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

查看ltrim和rtrim

你可以试试这个

  <?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];
      ?>