dongyue6199 2019-02-02 01:04
浏览 85
已采纳

在较近的SPACE和某个字符之间提取子字符串

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条回答 默认 最新

  • dongzhong3688 2019-02-02 01:07
    关注

    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') . "
    ";
    
    $str2 = 'SIM UMTS ITALIA IPHONE 2 MEGAPIXEL';
    echo getStringBetween($str2, ' ', 'GB') . "
    ";
    
    $str3 = 'SIM UMTS ITALIA 15.5" BLACK';
    echo getStringBetween($str3, ' ', '"') . "
    ";
    

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3