提取接近的空间和特定字符之间的串

问题描述 投票:0回答:1

正如我不得不提取产品描述属性“英寸”,我需要提取其接近空间复发之间的子功能”。

这是WP插件全进口的PHP编辑器。

$str = "SIM UMTS ITALIA 15.5" BLACK";
$from = " ";
$to = '"';

function getStringBetween($str,$from,$to){

$sub = substr($str, strpos($str,$from)+strlen($from),strlen($str));
return substr($sub,0,strpos($sub,$to));
}

我预计:15.5

结果:15.5 UMTS SIM意大利

php substring extract
1个回答
0
投票

根据评论的答案,这是一个最好的解决方案,因为它会返回任何结果当没有匹配到$to字符串,而不是作为最初的解决方案做了整个字符串。

function getStringBetween($str,$from,$to){
    if (preg_match("/$from([^$from]+)$to/", $str, $matches))
        return $matches[1];
    else
        return '';
}

$str = 'SIM UMTS ITALIA 35GB BLACK';
echo getStringBetween($str, ' ', 'GB') . "\n";

$str2 = 'SIM UMTS ITALIA IPHONE 2 MEGAPIXEL';
echo getStringBetween($str2, ' ', 'GB') . "\n";

$str3 = 'SIM UMTS ITALIA 15.5" BLACK';
echo getStringBetween($str3, ' ', '"') . "\n";

输出:

35 

15.5

Demo on 3v4l.org

原来的答案

这可能是更容易改用preg_replace,寻找一些数字或"前一段时间,并去除串例如所有其它字符

$str = 'SIM UMTS ITALIA 15.5" BLACK';
echo preg_replace('/^.*?(\d+(\.\d+)?)".*$/', '$1', $str);

输出:

15.5

更一般地(如果$from是一个字符):

function getStringBetween($str,$from,$to){
    return preg_replace("/^.*$from([^$from]+)$to.*$/", '$1', $str);
}

Demo on 3v4l.org

© www.soinside.com 2019 - 2024. All rights reserved.