JavaScript, PHP keyword search function

Source: Internet
Author: User

  • Javascript:
    A. Code:
    /*@desc:js搜索函数,可用于关键字匹配@param key 关键字@param str 要搜索的字符串@return out 匹配关键字前后出现的位置*/function search(key,str){var min = 0var max = str.lengthvar index = str.indexOf(key)var left = index - 10var right = index + 10if(left<min){    left = min}if(right>max){    right = max}var out = str.slice(left,right)return out}

    B. Testing:

    var str = ‘你好吗?你在哪里呀?我可以过来找你玩吗?你怎么不回答我呀!‘var key = ‘玩‘var res = search(key,str)console.log(res)

    C. Output:

    里呀?我可以过来找你玩吗?你怎么不回答我
  • Php:
    A. Code:
    <?php/*@desc:php搜索函数,可用于关键字匹配@param key 关键字@param str 要搜索的字符串@return out 匹配关键字前后出现的位置*/function search($key,$str){$min = 0;$max = mb_strlen($str);$index = mb_strpos($str,$key);$left = $index - 10;$right = $index + 10;if($left<$min){    $left = $min;}if($right>$max){    $right = $max;}$len = $right - $left;$out = mb_substr($str,$left,$len);return $out;}

    B. Testing:

    $str = ‘你好吗?你在哪里呀?我可以过来找你玩吗?你怎么不回答我呀!‘;$key = ‘玩‘;$res = search($key,$str);echo $res;

    C. Output:

    里呀?我可以过来找你玩吗?你怎么不回答我
  • JavaScript, PHP keyword search function

    Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.