AR_HZ
AR_HZ

Reputation: 365

PHP read everything until first comma

I have string that will look like this:

$string = "hello, my, name, is, az";  

Now I just wanna echo whatever is there before first comma. I have been using following:

echo strstr($this->tags, ',', true);

and It has been working great, but the problem it only works php 5.3.0 and above. I am currently on PHP 5.2.

I know this could be achieve through regular express by pregmatch but I suck at RE.

Can someone help me with this.

Regards,

Upvotes: 2

Views: 7394

Answers (6)

Rikesh
Rikesh

Reputation: 26431

Use explode than,

$arr = explode(',', $string,2);
echo $arr[0];

Upvotes: 6

Too much explosives for a small work.

$str = current(explode(',', $string));

Upvotes: -1

Álvaro González
Álvaro González

Reputation: 146460

<?php

$string = "hello, my, name, is, az";
echo substr($string, 0, strpos($string, ','));

You can (and should) add further checks to avoid substr if there's no , in the string.

Upvotes: 8

MISJHA
MISJHA

Reputation: 1008

You can simple use the explode function:

$string = "hello, my, name, is, az";
$output = explode(",", $string);
echo $output[0];

Upvotes: 1

chandresh_cool
chandresh_cool

Reputation: 11830

You can explode this string using comma and read first argument of array like this

$string = "hello, my, name, is, az";
$str = explode(",", $string, 2);
echo $str[0];

Upvotes: 2

dynamic
dynamic

Reputation: 48111

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

Upvotes: 1

Related Questions