PHP: Split string

PhpStringSplit

Php Problem Overview


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

Php Solutions


Solution 1 - Php

explode does the job:

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

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

list($part1, $part2) = explode('.', $string);

Solution 2 - Php

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

Solution 3 - Php

$string_val = 'a.b';

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

print_r($parts);

Documentation: explode

Solution 4 - Php

The following will return you the "a" letter:

$a = array_shift(explode('.', 'a.b'));

Solution 5 - Php

Use:

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

explode

Solution 6 - Php

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

Returns an array of split elements.

Solution 7 - Php

To explode with '.', use:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYoni MayerView Question on Stackoverflow
Solution 1 - PhpNikiCView Answer on Stackoverflow
Solution 2 - PhpDanView Answer on Stackoverflow
Solution 3 - PhpChris BakerView Answer on Stackoverflow
Solution 4 - PhpsmotttView Answer on Stackoverflow
Solution 5 - PhpdelphistView Answer on Stackoverflow
Solution 6 - PhpjondavidjohnView Answer on Stackoverflow
Solution 7 - PhpUjjwal ManandharView Answer on Stackoverflow