Terrorist Man Terrorist Man - 1 month ago 11
PHP Question

PHP: separate a string based on `|` delimiters

I am trying to figure out a way using PHP that I can parse a string of data from a URL to separate each entry based on the character

|
. Example data:


66.85.14.212:7254|108.174.48.186:8340|72.46.152.194:15240|162.248.91.125:7266|91.121.83.48:7619|185.153.228.114:5775|


Anyone got any ideas?

Answer

You can use the explode() function to split the string and remove empty elements with array_filter()

$string = '66.85.14.212:7254|108.174.48.186:8340|72.46.152.194:15240|162.248.91.125:7266|91.121.83.48:7619|185.153.228.114:5775|';
$ips = array_filter(explode('|', $string));

which results in an array containing all your ip adresses

Array
(
    [0] => 66.85.14.212:7254
    [1] => 108.174.48.186:8340
    [2] => 72.46.152.194:15240
    [3] => 162.248.91.125:7266
    [4] => 91.121.83.48:7619
    [5] => 185.153.228.114:5775
)

There are also two other functions, split() and preg_split() which supports regular expressions too.

Comments