PHP preg_split: Split string by forward slash

Zakaria Acharki picture Zakaria Acharki · Nov 10, 2015 · Viewed 14.6k times · Source

I want to split my string 192.168.1.1/24 by forward slash using PHP function preg_split.

My variable :

$ip_address = "192.168.1.1/24";

I have tried :

preg_split("/\//", $ip_address); 
//And
preg_split("/[/]/", $ip_address); 

Error message : preg_split(): Delimiter must not be alphanumeric or backslash

I found the following answer here in stackoverflow Php preg_split for forwardslash?, but it not provide a direct answer.

Answer

Alex Andrei picture Alex Andrei · Nov 10, 2015

Just use another symbol as delimiter

$ip_address = "192.168.1.1/24";

$var = preg_split("#/#", $ip_address); 

print_r($var);

will output

Array
(
    [0] => 192.168.1.1
    [1] => 24
)