使用 preg_replace 替换第一个匹配项
Replace first match using preg_replace
我需要从产品描述中提取第一次出现的 gigabyte 属性。
使用我的正则表达式 preg_rex 函数,它替换了最后一个匹配项,但我需要替换第一个匹配项(仅第一个)。
这用于从 CSV 文件导入产品。
function getStringBetween($str, $to, $from){
echo preg_replace("/^.*$from([^$from]+)$to.*$/", '', $str);
}
$str = 'NGM YOU COLOR P550 DUAL SIM 5.5" IPS HD CURVO QUAD CORE 8GB RAM 1GB 4G LTE';
getStringBetween($str, "GB", " ");
来自字符串:"NGM YOU COLOR P550 DUAL SIM 5.5" IPS HD CURVO QUAD CORE 8GB RAM 1GB 4G LTE"
我预计:8
它returns 1
介于两者之间的正则表达式可能有点困难。我建议使用量词 \d+
指定您要专门查找数字字符,并使用 preg_match
获取第一个结果:
<?php
function getFirstGB($str){
if (preg_match("/(\d+)GB/", $str, $matches)) {
return $matches[1];
} else {
return false;
}
}
$str = 'NGM YOU COLOR P550 DUAL SIM 5.5" IPS HD CURVO QUAD CORE 8GB RAM 1GB 4G LTE';
echo getFirstGB($str);
PHP游乐场here.
我需要从产品描述中提取第一次出现的 gigabyte 属性。 使用我的正则表达式 preg_rex 函数,它替换了最后一个匹配项,但我需要替换第一个匹配项(仅第一个)。
这用于从 CSV 文件导入产品。
function getStringBetween($str, $to, $from){
echo preg_replace("/^.*$from([^$from]+)$to.*$/", '', $str);
}
$str = 'NGM YOU COLOR P550 DUAL SIM 5.5" IPS HD CURVO QUAD CORE 8GB RAM 1GB 4G LTE';
getStringBetween($str, "GB", " ");
来自字符串:"NGM YOU COLOR P550 DUAL SIM 5.5" IPS HD CURVO QUAD CORE 8GB RAM 1GB 4G LTE"
我预计:8
它returns 1
介于两者之间的正则表达式可能有点困难。我建议使用量词 \d+
指定您要专门查找数字字符,并使用 preg_match
获取第一个结果:
<?php
function getFirstGB($str){
if (preg_match("/(\d+)GB/", $str, $matches)) {
return $matches[1];
} else {
return false;
}
}
$str = 'NGM YOU COLOR P550 DUAL SIM 5.5" IPS HD CURVO QUAD CORE 8GB RAM 1GB 4G LTE';
echo getFirstGB($str);
PHP游乐场here.