PHP 搜索获取文本之前/之后

标签 php mysql

我该如何将我的搜索结果变成这样的: http://i.stack.imgur.com/NfPGs.png

结果显示特定术语在单元格中的位置。

我目前有这个基本的搜索脚本:

      $terms = explode("-", $SQuery);
    $QuerySQL = "SELECT * FROM pages WHERE ";

        foreach ($terms as $each){
        $i++;

        if ($i == 1)
            $QuerySQL .= "Title LIKE '%$each%' OR Content LIKE '%$each%' OR Description LIKE '%$each%'";
        else 
            $QuerySQL .= "OR Title LIKE '%$each%' OR Description LIKE '%$each%' OR Content LIKE '%$each%'";
        }

    $QueryNEW = mysql_query($QuerySQL);

WHILE($datarows_cat = mysql_fetch_array($QueryNEW)):

        $title = $datarows_cat['Title'];
        $Deleted = $datarows_cat['Deleted'];
        $id = $datarows_cat['ID'];
        if ($Deleted != "YES") {
        echo "<a href='/{$id}'>{$title}</a><br/>";

}

最佳答案

您可以使用 PHP strpos查找 +/- 100 个字符:

$pos = strpos($mystring, $findme);

if ($pos === false) {
    echo "The string '$findme' was not found in the string '$mystring'";
} else {
    echo "The string '$findme' was found in the string '$mystring'";
    echo " and exists at position $pos";
}

然后使用PHP substr获取 $pos+100$pos-100

的子串
//For instance your substring could start at the position of the word found minus 100 characters and a length of 200
$result = substr($mystring, $pos-100, 200);

您可以使用 PHP str_replace格式化你需要的字符串:

$word_your_looking_for = "test";
$word_you_want_to_replace_it_with = "<b>test</b>"; //Make it bold

str_replace($word_your_looking_for, $word_you_want_to_replace_it_with, $your_string);

关于PHP 搜索获取文本之前/之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14944138/

相关文章:

php - 镜像网站时仅复制更改的文件

php - 使用 Php Stomp 使用 Ssl 的 ActiveMq 问题

php - 无法使用 MysqliDb 更新字段

php - MySQL:时间轴脚本,添加用户帖子和我自己的帖子

mysql - 如何从 .ibd 文件重新创建 MySQL InnoDB 表?

php - MySql:不可更改的时区

php - 如何保护本地托管网站的源代码?

php - 具有多个字值的选项标签

php - 势不可挡的循环 X(

php - mysql_num_rows() 期望参数 1 是资源,在中给出的 bool 值