String php explode string based on characters according to string condition

I have lines like this:

$string1 = '35 Hose & Couplings/350902 GARDEN HOSE COUPLING, PVC, 16\/19 MM"'; $string2 = '35 Hose & Couplings/350904 GARDEN HOSE TAP CONNECTOR, PVC, 3\/4" FEMALE THREAD"'; 

I tried to separate the string and turn it into an array like this:

 $name1 = explode('/', $string1); $name1 = trim(end($name1)); $name2 = explode('/', $string2); $name2 = trim(end($name2)); /* #results $name1[0] = '35 Hose & Couplings'; $name1[1] = '350902 GARDEN HOSE COUPLING, PVC, 16\'; $name1[2] = '19 MM"'; ... #expected results $name1[0] = '35 Hose & Couplings'; $name1[1] = '350902 GARDEN HOSE COUPLING, PVC, 16\/19 MM"'; ... */ 

I want to blow the line when there is only / , but when it encounters \/ , it should not insert the line, my code still blows the line if it contains \/ , is there any way to do this?

+5
source share
2 answers

You can use regex with negative appearance:

 $parts = preg_split('~(?<!\\\\)/~', $string1); 

See example eval.in

+3
source

You can go like this:

 $string1 = str_replace("\/","@",$string1); $name1 = explode('/', $string1); foreach($name1 as $id => $name) { $name1[$id] = str_replace("@","\/",$name1[$id]); } 

a little cumbersome, I know, but I have to do the trick. Wrap it in a function for better readability.

Basically, I replaced the line you don't want to explode with a temporary line and brought it back after the explosion.

+1
source

Source: https://habr.com/ru/post/1275580/


All Articles