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?
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.
The explode() function breaks a string into an array. Note: The "separator" parameter cannot be an empty string. Note: This function is binary-safe.
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.
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.
You could use a regular expression with negative look-behind:
$parts = preg_split('~(?<!\\\\)/~', $string1);
See example on eval.in
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With