Extract a substring betwen the closer SPACE and a certain character

佐手、 提交于 2020-01-06 06:37:07

问题


As I have to extract the attribute 'inches' from products description, I need a function that extract substring between its closer space recurrence and ".

This is for PHP editor of the WP plugin All-Import.

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

I excpected: 15.5

Results: SIM UMTS ITALIA 15.5


回答1:


Based on comments to the answer, this is a preferable solution, as it will return nothing when there is no match to the $to string instead of the entire string as the original solution did.

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";

Output:

35 

15.5

Demo on 3v4l.org

Original Answer

It is probably easier to use preg_replace instead, looking for some digits or a period before a " and removing all other characters from the string e.g.

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

Output:

15.5

More generically (if $from is a character):

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

Demo on 3v4l.org



来源:https://stackoverflow.com/questions/54489030/extract-a-substring-betwen-the-closer-space-and-a-certain-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!