php mysql 只保留单词和标点符号,不带制表符、换行符等
php mysql keep only words ans punctuation without tabs, new lines, etc
我有一个数据库,里面装满了来自不同来源和语言的 rss 提要项目的标题和描述...
这道题不是关于空格,而是关于保留单词和标点符号的问题。
我试图只保留带有标点符号的单词,例如 ' " , . ; ( ) ! ?
并删除制表符、双空格、换行符等。
我有一个部分有效的解决方案,但在我的数据库中我仍然看到新行段落、空新行...
我还删除了标签,因为我只想保留文本。
$onlywords = strip_tags(html_entity_decode($insUrlsOk['rss_summary'])); //html_entity_decode because some times it's < instead of <
$onlywords = trim($onlywords); // works partially -->> I still have new lines paragraphs, empty new lines
$onlywords = preg_replace('/[^\w\s]+/u',' ',$onlywords); //keeps ONLY words from any langages but also remove punctuation
$onlywords = str_replace(' ',' ',$onlywords);
我觉得我的 preg 模式 '/[^\w\s]+/u'
需要更精致一点...
我也愿意接受其他解决方案,只要它很短并且保持在几行代码之内(无需在服务器中安装额外的插件)。
谢谢。
trim()
只去掉字符串开头和结尾的白色space,所以不会去掉段落。
换行符和制表符包含在 \s
中,因此 preg_replace()
保留它们。使用 preg_replace
而不是 str_replace
将所有白色序列 space 变成单个 space:
$onlywords = preg_replace('/\s{2,}/', ' ', $onlywords);
我有一个数据库,里面装满了来自不同来源和语言的 rss 提要项目的标题和描述...
这道题不是关于空格,而是关于保留单词和标点符号的问题。
我试图只保留带有标点符号的单词,例如 ' " , . ; ( ) ! ? 并删除制表符、双空格、换行符等。
我有一个部分有效的解决方案,但在我的数据库中我仍然看到新行段落、空新行... 我还删除了标签,因为我只想保留文本。
$onlywords = strip_tags(html_entity_decode($insUrlsOk['rss_summary'])); //html_entity_decode because some times it's < instead of <
$onlywords = trim($onlywords); // works partially -->> I still have new lines paragraphs, empty new lines
$onlywords = preg_replace('/[^\w\s]+/u',' ',$onlywords); //keeps ONLY words from any langages but also remove punctuation
$onlywords = str_replace(' ',' ',$onlywords);
我觉得我的 preg 模式 '/[^\w\s]+/u'
需要更精致一点...
我也愿意接受其他解决方案,只要它很短并且保持在几行代码之内(无需在服务器中安装额外的插件)。
谢谢。
trim()
只去掉字符串开头和结尾的白色space,所以不会去掉段落。
换行符和制表符包含在 \s
中,因此 preg_replace()
保留它们。使用 preg_replace
而不是 str_replace
将所有白色序列 space 变成单个 space:
$onlywords = preg_replace('/\s{2,}/', ' ', $onlywords);