用PHP脚本自动把纯文本文件转换成Web页面_PHP教程

php中文网
发布: 2016-07-20 11:05:38
原创
986人浏览过

最近,我的一个老朋友向我打电话求助。他从事记者的职业有多年了,最近获得了重新出版他的很多早期专栏的权利。他希望把他的作品贴在web上;但是他的专栏都是以纯文本文件的形式保存的,而且他既没有时间也不想去为了把它们转换成为web页面而学习html的知识。由于我是他电话本里唯一一个精通计算机的人,所以他打电话给我看我是否能够帮帮他。

“让我来处理吧,”我说:“一个小时以后再给我打电话。”当然了,当他几个小时以后打电话过来,我已经为他预备好了解决的方法。这需要用到一点点php,而我收获了他没完没了的感谢和一箱红酒。

那么我在这一个小时里做了些什么呢?这就是本篇文章的内容。我将告诉你如何使用php来快速将纯ascii文本完美地转换成为可读的html标记。

首先让我们来看一个我朋友希望转换的纯文本文件的例子:

green for mars!
john r. doe

the idea of little green men from mars, long a staple of science fiction, may soon turn out to be less fantasy and more fact.

recent samples sent by the latest mars exploration team indicate a high presence of chlorophyll in the atmosphere. chlorophyll, you will recall, is what makes plants green. it's quite likely, therefore, that organisms on mars will have, through continued exposure to the green stuff, developed a greenish tinge on their outer exoskeleton.

an interview with dr. rushel bunter, the head of asda's mars colonization project blah blah...

what does this mean for you? well, it means blah blahblah...

track follow-ups to this story online at http://www.mars-connect.dom/. to see pictures of the latest samples, log on to http://www.asdamcp.dom/galleries/220/

相当标准的文本:它有一个标题、一个署名和很多段的文字。把这篇文档转换成为html真正需要做的是使用html的分行和分段标记把原文的布局保留在web页面上。非凡的标点符号需要被转换成为对应的html符号,超链接需要变得可以点击。

下面的php代码(列表a)就会完成上面所有的任务:

列表a

// set source file name and path
$source = "toi200686.txt";

// read raw text as array
$raw = file($source) or die("cannot read file");

// retrieve first and second lines (title and author)
$slug = array_shift($raw);
$byline = array_shift($raw);

// join remaining data into string
$data = join('', $raw);

// replace special characters with html entities
// replace line breaks with

$html = nl2br(htmlspecialchars($data));

// replace multiple spaces with single spaces
$html = preg_replace('/ss /', ' ', $html);

BetterYeah AI
BetterYeah AI

基于企业知识库构建、训练AI Agent的智能体应用开发平台,赋能客服、营销、销售场景 -BetterYeah

BetterYeah AI 110
查看详情 BetterYeah AI

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/445115.htmlTechArticle最近,我的一个老朋友向我打电话求助。他从事记者的职业有多年了,最近获得了重新出版他的很多早期专栏的权利。他希望把他的作品贴...
相关标签:
php
PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号