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 '/'.

Answer Source

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);