提取距离更近的SPACE和某个字符之间的子字符串 [英] Extract a substring betwen the closer SPACE and a certain character

查看:79
本文介绍了提取距离更近的SPACE和某个字符之间的子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我必须从产品描述中提取属性"inches",因此我需要一个函数来提取其较小的空间重复出现次数和."之间的子字符串.

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

这是WP插件全导入"的PHP编辑器.

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

我期望:15.5

结果:SIM UMTS ITALIA 15.5

Results: SIM UMTS ITALIA 15.5

推荐答案

基于答案的注释,这是一个更可取的解决方案,因为当与$to字符串不匹配而不是整个字符串都不匹配时,它将不返回任何内容字符串,就像原始解决方案一样.

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

输出:

35 

15.5

在3v4l.org上进行演示

原始答案

相反,使用preg_replace可能更容易,在"之前查找一些数字或句点,然后从字符串中删除所有其他字符,例如

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

输出:

15.5

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

More generically (if $from is a character):

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

在3v4l.org上进行演示

这篇关于提取距离更近的SPACE和某个字符之间的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆