search array - php
Im trying to work out how to search a string looking for a given variable, and if it is longer t开发者_JAVA百科han two charachters, and exists in the array, return that string with the search word highlighted in some way. Ive been trying for two days and its not coming out right, any help will be very welcome!
my php:
$search = $_POST ['search'];
$text = 'some long text containg several words.';
$search = trim($search);
$search = strtolower($search);
$text = explode($text);
if ((in_array($search, $text)) && ($search >= 2)){
echo $text;
}else{
echo "no result or too short search word";
}
and my html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>word for which to search:</P>
<form action="searchfunction.php" method="post">
<input type="text" name="search" /><br />
<input type="submit" />
</form>
</body>
</html>
There seems to be no need to explode()
into an array at all. Just use strpos()
to locate the search string and strlen()
to make sure it's more than 2 characters.
$search = trim($_POST['search']);
$text = 'some long text containg several words.';
// Search for $search inside $text as a string
// Both converted to lowercase only for the search
if (strpos(strtolower($text), strtolower($search)) !== FALSE && strlen($search) >= 2){
echo $text;
}else{
echo "no result or too short search word";
}
Now to handle your highlighting. The easiest way to do that is to use str_ireplace()
to surround it in a <span>
. You would need to define the class 'highlight' in you CSS file to have some special color.
// If your text was found...
$text = str_ireplace($search, "<span class='highlight'>$search</span>", $text);
echo $text;
Instead of
if ((in_array($search, $text)) && ($search >= 2)){
can you try
if ((in_array($search, $text)) && (strlen($search) >= 2)){
Also, explode needs to take the first argument as " ". So you have to call it as
$text = explode(" ", $text)
length function using in following line
if ((in_array($search, $text)) && ($search >= 2)){
in above line their is need some modifications
if ((in_array($search, $text)) && (strlen($search) >= 2)){
explode() expects at least 2 parameters
$text = explode(' ', $text);
Perhaps
$text = explode($text);
if ((in_array($search, $text)) && ($search >= 2)){
...should be...
$text = explode(' ', $text);
if ((in_array($search, $text)) && (strlen($search) >= 2)){
It's also possible to achieve your goal without using arrays, for example by using a regular expression match:
$search = $_POST['search'];
if (strlen($search) < 2) {
echo "too short search word";
} else {
$text = 'some long text containg several words.';
$pattern = '/\b' . preg_quote($search, '/') . '\b/i';
if (preg_match($pattern, $text, $matches)) {
echo $matches[0];
} else {
echo "no result";
}
}
精彩评论