77

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
  • 80,501
  • 25
  • 149
  • 167
Yoni Mayer
  • 1,118
  • 1
  • 12
  • 26

7 Answers7

150

explode does the job:

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

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

list($part1, $part2) = explode('.', $string);
NikiC
  • 98,796
  • 35
  • 186
  • 223
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,030
  • 21
  • 100
  • 124
Dan
  • 3,316
  • 1
  • 21
  • 27
10
$string_val = 'a.b';

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

print_r($parts);

Documentation: explode

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Chris Baker
  • 48,371
  • 12
  • 98
  • 115
8

The following will return you the "a" letter:

$a = array_shift(explode('.', 'a.b'));
smottt
  • 3,182
  • 11
  • 38
  • 43
6

Use:

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

explode

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
delphist
  • 4,367
  • 1
  • 21
  • 22
5
$array = explode('.',$string);

Returns an array of split elements.

jondavidjohn
  • 60,871
  • 21
  • 115
  • 157
-1

To explode with '.', use:

explode('\\.', 'a.b');
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Ujjwal Manandhar
  • 2,158
  • 16
  • 20