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.

3
  • 5
    explode('/', "192.168.1.1/24") Commented Nov 10, 2015 at 10:12
  • 4
    preg_split("/\//", $ip_address); should work fine. It does for me. Commented Nov 10, 2015 at 10:16
  • This question is off-topic: No Repro because the asked question contains a working implementation. Commented Apr 14, 2024 at 0:10

3 Answers 3

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
)
Sign up to request clarification or add additional context in comments.

3 Comments

Not work for me: var_dump(preg_split("#/#/#","12/34/5678")); will return bool(false)
if you use it like this var_dump(preg_split("#/#","12/34/5678")); it will return the three strings separated by /
For fun - see php.net/manual/en/regexp.reference.delimiters.php for the available delimiters. e.g. var_dump(preg_split("(/)", "192.168.1.1/24")).
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
)

Comments

2

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

2 Comments

I'm sorry but I wanna use preg_split as described in my question using PHP function preg_split.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.