Reputation: 69
I need to extract the first occurence of gigabyte attribute from product description. With my regex preg_rex function it replace last match but I need to replace the first match (only the first).
This is for importing products from CSV files.
function getStringBetween($str, $to, $from){
echo preg_replace("/^.*$from([^$from]+)$to.*$/", '$1', $str);
}
$str = 'NGM YOU COLOR P550 DUAL SIM 5.5" IPS HD CURVO QUAD CORE 8GB RAM 1GB 4G LTE';
getStringBetween($str, "GB", " ");
From the string: "NGM YOU COLOR P550 DUAL SIM 5.5" IPS HD CURVO QUAD CORE 8GB RAM 1GB 4G LTE"
I expect: 8
It returns 1
Upvotes: 0
Views: 179
Reputation: 22911
In between with regex can be a bit difficult. I recommend using the quantifer \d+
to specify you're looking specifically for a digit character, and use preg_match
to fetch the first result:
<?php
function getFirstGB($str){
if (preg_match("/(\d+)GB/", $str, $matches)) {
return $matches[1];
} else {
return false;
}
}
$str = 'NGM YOU COLOR P550 DUAL SIM 5.5" IPS HD CURVO QUAD CORE 8GB RAM 1GB 4G LTE';
echo getFirstGB($str);
PHP Playground here.
Upvotes: 1