Home > Backend Development > PHP Tutorial > How to use JavaScript and PHP keyword search functions

How to use JavaScript and PHP keyword search functions

青灯夜游
Release: 2023-04-04 08:56:01
forward
2453 people have browsed it

This article mainly introduces relevant information on how to use JavaScript and PHP keyword search functions. Friends in need can refer to it.

javascript:

a. Code:

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

b. Test:

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

c. Output:

Where? Can I come over and play with you? Why don't you answer me

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;
}
Copy after login

b. Test:

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

c. Output: Where is

? Can I come over and play with you? Why don't you answer me?

The above is the entire content of this chapter. For more related tutorials, please visit php programming from entry to master full set of video tutorials, JavaScript video tutorial!

The above is the detailed content of How to use JavaScript and PHP keyword search functions. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:jb51.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template