Skip to content
Advertisement

Return a substring of a string if exists

I need to extract console platform from the description of products in CSV file.

I used regex to match all the console brands that are included in the list.

This is for WP All-Import plugin PHP editor widget.

$haystack = "NINTENDO MARIO KART 7 XBOX-360 SPECIAL EDITION";

echo preg_replace('/(PS4b)|(bPS3b)|(bSWITCHb)|(bXBOX b)|(bXBOX-360b)|(bXBOX-ONEb)|
(bPCb)|(bPSPb)|(bWII b)|(bWII-Ub)|(b3DSb)|(b2DSb)|(bNINTENDO-DSb)/', '$1', $haystack);

I expect: XBOX-360

It returns the rest of the string except what I expect: NINTENDO MARIO KART 7 SPECIAL EDITION

Advertisement

Answer

You can use preg_match. The $ result [0] variable will be the result

$haystack = "NINTENDO MARIO KART 7 XBOX-360 SPECIAL EDITION";

preg_match('/(PS4b)|(bPS3b)|(bSWITCHb)|(bXBOX b)|(bXBOX-360b)|(bXBOX-ONEb)|
(bPCb)|(bPSPb)|(bWII b)|(bWII-Ub)|(b3DSb)|(b2DSb)|(bNINTENDO-DSb)/', $haystack, $result);
echo $result[0];
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement