0

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

4

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.