从php中的字符串第一个逗号后删除所有内容

hal*_*sed 7 php

我想删除PHP中字符串的第一个逗号中的所有内容(包括逗号).

$print="50 days,7 hours";
Run Code Online (Sandbox Code Playgroud)

应该成为"50天"

Pau*_*xon 27

这是一种方式:

$print=preg_replace('/^([^,]*).*$/', '$1', $print);
Run Code Online (Sandbox Code Playgroud)

另一个

list($firstpart)=explode(',', $print);
Run Code Online (Sandbox Code Playgroud)

  • 对于简单的字符串操作,正则表达式似乎有点矫枉过正? (3认同)
  • 正则表达式是针对蚊子问题的一个canon-ball解决方案 (3认同)

sch*_*ick 11

这应该适合你:

$r = (strstr($print, ',') ? substr($print, 0, strpos($print, ',')) : $print);
# $r contains everything before the comma, and the entire string if no comma is present
Run Code Online (Sandbox Code Playgroud)

  • 这个例如给定,但如果字符串不包含逗号则会失败. (2认同)

Mat*_*ves 6

你可以使用正则表达式,但是如果它总是与逗号一起配对,我就这样做:


$printArray = explode(",", $print);
$print = $printArray[0];
Run Code Online (Sandbox Code Playgroud)

  • 你的意思是$ printArray [0]吗? (3认同)

Nar*_*rek 5

您还可以使用当前功能:

$firstpart = current(explode(',', $print)); // will return current item in array, by default first
Run Code Online (Sandbox Code Playgroud)

此系列的其他功能:

$nextpart = next(explode(',', $print)); // will return next item in array

$lastpart = end(explode(',', $print)); // will return last item in array
Run Code Online (Sandbox Code Playgroud)