MySQL从html数据或PHP提取纯文本? [英] MySQL extract plaintext from html data or PHP?
问题描述
作为标题,如果我插入一些html到表中。如何使用mysql在html标签之间提取明文?
例如:
As the title, if I insert some html into the table. How can I use mysql to extract the plaintext between the html tags?
For example:
CREATE TABLE `test`
(
`id` INT PRIMARY KEY,
`plain` LONGTEXT
)
INSERT INTO `text` VALUES (1, '<p>text between tag 'p'</p><span>text between 'span'</span>');
在插入之前,我想使用触发器来提取我想要的纯文本。如何?
或使用php?我的意思是传递html到一个php脚本和php脚本做提取。
And before insert, I want to use a trigger to extract the plain text I want. How to?
Or use php ? I mean pass the html to a php script and the php script does the extraction.
推荐答案
如果你的内容总是以标签开头(etc。)
请尝试:
SELECT * from table WHERE colmn_name REGEXP '>[^<]*mytext';
另一种方法是使用 strip_tags
- 从字符串中分离HTML和PHP标签
Another way is to use strip_tags
— Strip HTML and PHP tags from a string
<?php
$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo strip_tags($text);
echo "\n";
// Allow <p> and <a>
echo strip_tags($text, '<p><a>');
?>
上述代码的输出:
Test paragraph. Other text
<p>Test paragraph.</p> <a href="#fragment">Other text</a>
警告 :: 不实际验证HTML,部分或破损的标签可能会导致删除比预期更多的文本/数据。
变量中的代码,让我们说 $ html_input
You should put the html code in a variable, let's say $html_input
$html_input= "'<p>text between tag 'p'</p><span>text between 'span'</span>'";
$stripped_html = strip_tags($html_input);
// Now insert it into the table `text`
INSERT INTO `text` VALUES (1, $striped_html);
纯粹 MQSQL
/ strong>
Purely MQSQL
way:
CREATE FUNCTION `strip_tags`($str text) RETURNS text
BEGIN
DECLARE $start, $end INT DEFAULT 1;
LOOP
SET $start = LOCATE("<", $str, $start);
IF (!$start) THEN RETURN $str; END IF;
SET $end = LOCATE(">", $str, $start);
IF (!$end) THEN SET $end = $start; END IF;
SET $str = INSERT($str, $start, $end - $start + 1, "");
END LOOP;
END;
mysql> select strip_tags('<span>hel<b>lo <a href="world">wo<>rld</a> <<x>again<.');
+----------------------------------------------------------------------+
| strip_tags('<span>hel<b>lo <a href="world">wo<>rld</a> <<x>again<.') |
+----------------------------------------------------------------------+
| hello world again. |
+----------------------------------------------------------------------+
1 row in set
参考: Stackoverflow
这篇关于MySQL从html数据或PHP提取纯文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!