如何从另一个字符串中提取一个字符串 php

How do I extract a string from another string php

我想从另一个字符串中提取一个字符串,但我唯一能看到的是 substr(),它在我的字符串长度不同时使用整数。

看看字符串,我有一堆这样的字符串,我想提取并仅在它们存在的情况下回显额外内容。我怎样才能用 PHP 做到这一点。谢谢大家。

$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...

   }
}

所以目前的功能只是检查单词 'Extras:' 是否存在,在这种情况下我只想回显 'Sennheiser CX 2.00i (Black)'

试试这个:

if (preg_match("(?<=Extras:).*", $string, $matches)) {
    print_r($matches);
} else {
    echo "A match was not found.";
}

正则表达式是个好主意,替代方法是普通的旧爆炸:

$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];
    }

输出"Sennheiser CX 2.00i (Black)"

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

// 'Extras:' is 7 chars
$extras = substr($string, strpos($string, 'Extras:') + 7);

echo $extras;

OUTPUT: Sennheiser CX 2.00i (Black)

有可能。一种更简单的方法,但如果您一直在寻找 'Extras:' strpos() returns an int.

之后的内容,则它会起作用