PHP strip_tags到MySQL搜索查询

时间:2014-12-08 04:47:53

标签: php mysql search-engine

我需要知道如何应用strip_tags函数来忽略post.post中标记中的搜索 http://php.net/manual/en/function.strip-tags.php

$searchTerm = $db->real_escape_string($_GET['s']);
if(!empty($searchTerm)) {
    // Get search result algorithim to list by weight of title first, content second
    $q = $db->query("SELECT posts.id, posts.title, posts.date, posts.tags, posts.image, users.name, users.screen_name, users.id as user_id,
        IF(
            posts.title LIKE '$searchTerm%',  20, 
            IF(posts.title LIKE '%$searchTerm%', 10, 0)
        )
        + IF(posts.post LIKE '%$searchTerm%', 5,  0)
        AS weight
    FROM posts
    LEFT JOIN users ON posts.user_id=users.id
    WHERE (
        posts.title LIKE '%$searchTerm%' 
        OR posts.post LIKE '%$searchTerm%'
    )
    AND posts.status = 1
    ORDER BY weight DESC
    LIMIT 12");
    $r = $q->fetch_all(MYSQLI_ASSOC);
    $smarty->assign("posts", $r);
}

2 个答案:

答案 0 :(得分:2)

你可以在sql中通过在我的sql中创建一个单独的函数并在查询中使用它来实现。请查看以下示例,

对于Ex:

Custom Function `strip_tags()`

delimiter ||
DROP FUNCTION IF EXISTS strip_tags||
CREATE FUNCTION strip_tags( x longtext) RETURNS longtext
LANGUAGE SQL NOT DETERMINISTIC READS SQL DATA
BEGIN
DECLARE sstart INT UNSIGNED;
DECLARE ends INT UNSIGNED;
SET sstart = LOCATE('<', x, 1);
REPEAT
SET ends = LOCATE('>', x, sstart);
SET x = CONCAT(SUBSTRING( x, 1 ,sstart -1) ,SUBSTRING(x, ends +1 )) ;
SET sstart = LOCATE('<', x, 1);
UNTIL sstart < 1 END REPEAT;
return x;
END;
||
delimiter ;


SELECT strip_tags('<div style="font-size:12px">This is a body area</div>') as stripped_text;

答案 1 :(得分:0)

我刚添加了2行,以避免在字符串

中找不到htmltags时出错
BEGIN
DECLARE sstart INT UNSIGNED;
DECLARE ends INT UNSIGNED;
    SET sstart = LOCATE('<', x, 1);
    IF (sstart = 0) THEN RETURN x;
    END IF;
    REPEAT
       SET ends = LOCATE('>', x, sstart);
       SET x = CONCAT(SUBSTRING( x, 1 ,sstart -1) ,SUBSTRING(x, ends +1 )) ;
       SET sstart = LOCATE('<', x, 1);
    UNTIL sstart < 1 END REPEAT;
    RETURN x;
END