Search code examples
phpstringsubstr

How do I extract a string from another string php


I'd like to extract a string from another string but the only thing I could see was substr() which uses integers when my strings will be different lengths.

Take a look at the string, I have a bunch of these I want to extract and echo the extras only if they exist. How can I do this with PHP. Thanks guys.

$string = 'Apple iPhone 6 Plus (Refurbished 16GB Silver) on EE Regular 2GB (24 Month(s) contract) with UNLIMITED mins; UNLIMITED texts; 2000MB of 4G data. £37.49 a month. Extras: Sennheiser CX 2.00i (Black)';

function freegifts($string) {
   if (strpos($string, 'Extras:') !== false {

        extract extras...

   }
}

So the function at the moment just checks to see if the word 'Extras:' is present, in this case i'd just like to echo 'Sennheiser CX 2.00i (Black)'


Solution

  • a regular expression is a fine idea, an alternative is plain old explode:

    $string = 'Apple iPhone 6 Plus (Refurbished 16GB Silver) on EE Regular 2GB (24 Month(s) contract) with UNLIMITED mins; UNLIMITED texts; 2000MB of 4G data. £37.49 a month. Extras: Sennheiser CX 2.00i (Black)';
    
        $x=explode('Extras:',$string);
    
        if(!empty($x[1])){
        echo    $x[1];
        }
    

    output "Sennheiser CX 2.00i (Black)"