首先,我有一个像这样的动态字符串
,
有时喜欢这个
firstname,
有时也喜欢这样
,姓氏
我怎么能检测到如果string只包含逗号然后使字符串为空(删除逗号)else如果string包含firstname和逗号(没有lastname,请参阅下面的格式)
姓名,
然后删除字符串中的逗号并保留firstname else如果字符串包含逗号和lastname,则删除逗号并将lastname保留在字符串中。
有任何想法,帮助,线索,建议和建议吗?
答案 0 :(得分:2)
如果您的逗号只在字符串的开头和结尾处,那么您可以这样做:
$firstname = rtrim('firstname', ',');
$lastname = ltrim(', lastname', ', ');
答案 1 :(得分:2)
您可以使用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
希望我有所帮助!
答案 2 :(得分:1)
你可以试试这个
<?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];
?>