5

I have strings 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 explode the string when there is / only, but when it meets \/ it shouldn't explode the string, my code still explode the string if it contains \/, is there a way to do this?

revo
  • 47,783
  • 14
  • 74
  • 117
nortonuser
  • 215
  • 1
  • 7
  • 'i want to explode the string when there is '/' only, but when it meets '/' it will not explode the string'- what do you mean ? – Istiaque Ahmed Feb 26 '18 at 10:48
  • @IsThisJavascript Yes that's what i want – nortonuser Feb 26 '18 at 10:50
  • have you looked at preg_split (http://php.net/manual/de/function.preg-split.php) – EGOrecords Feb 26 '18 at 10:51
  • I think this is a job for regex, unfortunately my regex skills suck. Maybe you could try looking here for further assistance until someone can provide better guidance https://regexr.com/ – IsThisJavascript Feb 26 '18 at 10:52
  • 1
    You an either first "protect" the exception "\\/" by replacing it with some "magical" sequence and convert it back after having replaced the remaining "/" occurrances, or you use a regular expression with lookahead. – arkascha Feb 26 '18 at 10:54

2 Answers2

3

You could use a regular expression with negative look-behind:

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

See example on eval.in

trincot
  • 317,000
  • 35
  • 244
  • 286
1

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 should do the trick. Wrap it in a function for better readability.

Basically I replaced the string you do not want to explode by with a temporary string and reverted it back after exploding.

Michał Skrzypek
  • 699
  • 4
  • 14