8

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.

Community
  • 1
  • 1
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101

3 Answers3

20

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
)
Alex Andrei
  • 7,315
  • 3
  • 28
  • 42
  • Not work for me: var_dump(preg_split("#/#/#","12/34/5678")); will return bool(false) – Viet Tran Aug 04 '17 at 16:12
  • 1
    if you use it like this `var_dump(preg_split("#/#","12/34/5678"));` it will return the three strings separated by `/` – Alex Andrei Aug 07 '17 at 06:59
  • 1
    For fun - see https://www.php.net/manual/en/regexp.reference.delimiters.php for the available delimiters. e.g. `var_dump(preg_split("(/)", "192.168.1.1/24"))`. – Cameron Wilby May 12 '23 at 01:27
6

This is another way that meet up your solution

$ip_address = "192.168.1.1/24";
$var = preg_split("/\//", $ip_address);
print_r($var);

Output result

Array(
    [0] => 192.168.1.1
    [1] => 24
)
A.A Noman
  • 5,244
  • 9
  • 24
  • 46
2

You can use explode('/', "192.168.1.1/24");

Viet Tran
  • 1,173
  • 11
  • 16
  • I'm sorry but I wanna use `preg_split` as described in my question _using PHP function preg_split._ – Zakaria Acharki Aug 04 '17 at 16:31
  • Sorry, my bad. I was finding the way to split string and went to your question by google search. So I thought that you had the same problem with me. Sorry. – Viet Tran Aug 04 '17 at 17:45