79

How do I split a string by . delimiter in PHP? For example, if I have the string "a.b", how do I get "a"?

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
Yoni Mayer
  • 1,212
  • 1
  • 14
  • 27

7 Answers7

152

explode does the job:

$parts = explode('.', $string);

You can also directly fetch parts of the result into variables:

list($part1, $part2) = explode('.', $string);
NikiC
  • 100,734
  • 37
  • 191
  • 225
28

explode('.', $string)

If you know your string has a fixed number of components you could use something like

list($a, $b) = explode('.', 'object.attribute');
echo $a;
echo $b;

Prints:

object
attribute
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dan
  • 3,490
  • 2
  • 22
  • 27
9
$string_val = 'a.b';

$parts = explode('.', $string_val);

print_r($parts);

Documentation: explode

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Chris Baker
  • 49,926
  • 12
  • 96
  • 115
7

The following will return you the "a" letter:

$a = array_shift(explode('.', 'a.b'));
smottt
  • 3,272
  • 11
  • 37
  • 44
5

Use:

explode('.', 'a.b');

explode

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
delphist
  • 4,409
  • 1
  • 22
  • 22
4
$array = explode('.',$string);

Returns an array of split elements.

jondavidjohn
  • 61,812
  • 21
  • 118
  • 158
-1

To explode with '.', use:

explode('\\.', 'a.b');
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ujjwal Manandhar
  • 2,194
  • 16
  • 20