提取距离更近的SPACE和某个字符之间的子字符串 [英] Extract a substring betwen the closer SPACE and a certain character
问题描述
由于我必须从产品描述中提取属性"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
原始答案
相反,使用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);
}
这篇关于提取距离更近的SPACE和某个字符之间的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!