dtnmuyoiw680512744 2016-01-08 10:09
浏览 208
已采纳

如何在字符串中的特定关键字之前和之后提取单词?

I was wondering what the best way is to get the word before and after a specific keyword from a string?

Example:

$e = "Kuru Kavrulmuş soya Fasulye: 100 gram, ortalamadır";
$_GET['word'] = 'soya';

I would like to then echo out Kavrulmuş and Fasulye.

My dynamic snippet is (for getting string)

if ( stripos($e, $_GET['word']) !== false) {
    echo '<div class="yellow">'. highlight($e,$_GET['word']) . '</div>';
}

Any ideas?

  • 写回答

1条回答 默认 最新

  • dtnrsmi824877 2016-01-08 10:12
    关注

    You can use a simple regex with preg_match() to match the word before and after your keyword, e.g.

    $str = "Kuru Kavrulmuş soya Fasulye: 100 gram, ortalamadır"; 
    $_GET['word'] = 'soya';
    
    preg_match("/(\w+) " . $_GET['word'] . " (\w+)/mu", $str, $matches);
    
    print_r($matches);
    

    output:

    Array
    (
        [0] => Kavrulmuş soya Fasulye
        [1] => Kavrulmuş
        [2] => Fasulye
    )
    

    The regex simply explained is to use \w for word characters([a-zA-Z0-9_]) with a quantifier + to match 1 or more times. So you can capture the word before and after your keyword.

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部