用PHP指令碼自動把純文字檔案轉換成Web頁面_PHP教程

來源:互聯網
上載者:User
最近,我的一個老朋友向我打電話求助。他從事記者的職業有多年了,最近獲得了重新出版他的很多早期專欄的權利。他希望把他的作品貼在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);


http://www.bkjia.com/PHPjc/445115.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/445115.htmlTechArticle最近,我的一個老朋友向我打電話求助。他從事記者的職業有多年了,最近獲得了重新出版他的很多早期專欄的權利。他希望把他的作品貼...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.