How do I split a string by . delimiter in PHP? For example, if I have the string "a.b", how do I get "a"?
Asked
Active
Viewed 1.6e+01k times
77
Michał Perłakowski
- 80,501
- 25
- 149
- 167
Yoni Mayer
- 1,118
- 1
- 12
- 26
7 Answers
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
-1
To explode with '.', use:
explode('\\.', 'a.b');
Peter Mortensen
- 30,030
- 21
- 100
- 124
Ujjwal Manandhar
- 2,158
- 16
- 20