rockyraw
rockyraw

Reputation: 1145

Extract the first string before comma / Extract all if there's no comma at all

How should I modify the code, in the shortest way, in order to always echo the first string before comma, but if there's no comma at all, then echo the original string?

In the following code, for $string1 nothing is being echoed:

$string1 = "aaaaaaa";
echo '1';
echo substr($string1, 0, strpos($string1, ','));

$string2 = "aaaaaaa, bbbbb";
echo '2';
echo substr($string2, 0, strpos($string2, ','));

echo '3';
$string3 = "aaaaaaa, bbbbb, ccccc";
echo substr($string3, 0, strpos($string3, ','));

Upvotes: 0

Views: 65

Answers (2)

localroot
localroot

Reputation: 556

You can simply exploade the string and take first element.

$first_element = explode(',', $string)[0];

Upvotes: 0

iainn
iainn

Reputation: 17417

explode will return the entire string if the delimiter isn't found:

If delimiter contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned.

So this should work for all cases:

echo explode(',', $str)[0];

See https://eval.in/947792

Upvotes: 3

Related Questions