Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP preg_split: Split string by forward slash

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.

like image 640
Zakaria Acharki Avatar asked Nov 10 '15 10:11

Zakaria Acharki


People also ask

How do I split a string with a slash?

Use the str. rsplit() method to split the string on a slash, from the right. Get the list element at index 1 . The method will return a new string that only contains the part after the last slash.


2 Answers

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
)
like image 60
Alex Andrei Avatar answered Sep 21 '22 11:09

Alex Andrei


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
)
like image 23
A.A Noman Avatar answered Sep 23 '22 11:09

A.A Noman