-1

I need to remove the underscore and anything that comes after it. If there is no underscore the string should be left as it is. Is is possible?

$str1 = 'green_apples';
$str1 = substr($str1, 0, strpos($str1, '_'));
echo $str1; // green

Works fine until the string contains no underscore:

$str2 = 'yellow';
$str2 = substr($str2, 0, strpos($str2, '_'));
echo $str2; // should be 'yellow' but nothing is printed
sweet potato
  • 135
  • 1
  • 11

2 Answers2

1

That should work:

$str2 = 'yellow';
$pos = strpos($str2, '_');
$str2 = substr($str2, 0, $pos === false ? strlen($str2) : $pos);
echo $str2; // should be 'yellow' but nothing is printed
Thomas Ruiz
  • 3,611
  • 2
  • 20
  • 33
0

I would check if the _ exists before substringing it like so:

$str2 = !(strpos($str2, '_')===false) ? substr($str2, 0, strpos($str2, '_')) : $str2;
Micaiah Wallace
  • 1,101
  • 10
  • 17