dongyou2279 2013-10-30 11:04
浏览 14
已采纳

只有在包含确定子字符串时才获取字符串的一部分

I'm having problems to get a part of text only if it contains a substring. What i want to do is, given the next example:

1 - "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."

2 - "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut et dolore magna aliqua."

And with a substring like "labore", get "labore" and the prev and next 20 characters:

1 - "...empor incididunt ut labore et dolore magna ali..."

Edit: I am developing the search box for a website, so given a word i want to return all the paragraphs who contains that word, but the paragraphs are long so i want to return only a part of it.

  • 写回答

2条回答 默认 最新

  • douzang7928 2013-10-30 11:10
    关注

    I managed to get something like this. It's a bit long-winded.

    $string = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
    
    function searchStr($string, $search){
        if(strpos($string, $search) !== FALSE){
            echo "..." . substr($string, strpos($string, $search)-20, 20) . substr($string, strpos($string, $search), 20+strlen($search)) . "...";
        }
    }
    
    $res = searchStr($string, "labore");
    

    Returns

    ...empor incididunt ut labore et dolore magna ali...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP