Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php string explode string based on characters match with string condition

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?

like image 207
nortonuser Avatar asked Feb 26 '18 10:02

nortonuser


People also ask

How can I match a character in a string in PHP?

Definition and Usage. The strrchr() function finds the position of the last occurrence of a string within another string, and returns all characters from this position to the end of the string.

What does explode () do in PHP?

The explode() function breaks a string into an array. Note: The "separator" parameter cannot be an empty string. Note: This function is binary-safe.

How can I split a string into two strings in PHP?

explode() is a built in function in PHP used to split a string in different strings. The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string.

How many parameters does explode () function have?

The explode in PHP function accepts three parameters. One parameter is optional, and the other two are compulsory. These three parameters are as follows: delimiter: This character is the separator which specifies the point at which the string will be split.


2 Answers

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

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

See example on eval.in

like image 179
trincot Avatar answered Oct 16 '22 17:10

trincot


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.

like image 1
Michał Skrzypek Avatar answered Oct 16 '22 16:10

Michał Skrzypek