Krishnakumar Chandrasekharan Krishnakumar Chandrasekharan - 3 months ago 4x
PHP Question

Explode string with '/' and escape if it contains space around '/', like ' / '

How is it possible to explode a string using '/', if slash doesn't contain spaces before or after.

I wish the string like "Flat Visors / Fitted Caps" could be treated as a string and "Flat Visors/Fitted Caps" could be explode using '/'.


You can use preg_split with negative look-behind and negative look-ahead:

preg_split('/(?<!\s)\\/(?!\s)/', $str);

If you wish the opposite, i.e. splitting even when there is space around and remove the space, again with preg_split and optional space:

preg_split('/\s*\\/\s*/', $str);