php 从php中的字符串中删除第一个逗号之后的所有内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1131397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
remove everything after first comma from string in php
提问by halocursed
I want to remove everything(including the comma) from the first comma of a string in php eg.
我想从 php 中字符串的第一个逗号中删除所有内容(包括逗号),例如。
$print="50 days,7 hours";
should become "50 days "
应该变成“50天”
回答by Paul Dixon
Here's one way:
这是一种方法:
$print=preg_replace('/^([^,]*).*$/', '', $print);
Another
其他
list($firstpart)=explode(',', $print);
回答by schmilblick
This should work for you:
这应该适合你:
$r = (strstr($print, ',') ? substr($print, 0, strpos($print, ',')) : $print);
# $r contains everything before the comma, and the entire string if no comma is present
回答by Matthew Groves
You could use a regular expression, but if it's always going to be a single pairing with a comma, I'd just do this:
您可以使用正则表达式,但如果它总是与逗号配对,我会这样做:
$printArray = explode(",", $print);
$print = $printArray[0];
回答by Narek
You can also use currentfunction:
您还可以使用当前功能:
$firstpart = current(explode(',', $print)); // will return current item in array, by default first
Also other functions from this family:
该系列的其他功能还包括:
$nextpart = next(explode(',', $print)); // will return next item in array
$lastpart = end(explode(',', $print)); // will return last item in array
回答by ghostdog74
$string="50 days,7 hours";
$s = preg_split("/,/",$string);
print $s[0];

