使用PHP转换混合HTML文本[重复]

时间:2022-12-24 08:57:48

Possible Duplicate:
How to parse and process HTML with PHP?

可能重复:如何使用PHP解析和处理HTML?

Can somebody help me to find a solution to parse text which has HTML and regular text. For example

有人可以帮我找到解析具有HTML和常规文本的文本的解决方案。例如

This is my awesome <b>text</b>. Now <a href="http://google.com">starts</a> a new line...

<img src="http://example.com/image.png"/><br>
<br>
I push news to http://twitter.com .

This should become

这应该成为

This is my awesome <b>text</b>. Now <a href="http://google.com">starts</a> a new line...<br>
<br>
<img src="http://example.com/image.png"/><br>
<br>
I push news to <a href="http://twitter.com">twitter.com</a> .

I'm searching mainly for a magic regex replace function...At the moment I do

我正在寻找一个神奇的正则表达式替换功能...此刻我做了

$text = preg_replace("@(src|href)=\"https?://@i",'\\1="', $description);
$text = nl2br(preg_replace("@(((f|ht)tp:\/\/)[^\"\'\>\s]+)@",'<a href="\\1" target="_blank">\\1</a>', $text));

2 个解决方案

#1


3  

nl2br does the trick nicely.

nl2br做得很好。

file_get_contents('filename.html');
nl2br($text);

It was designed specifically for your needs.

它专为您的需求而设计。

If you're worried about double \ns or already present <br /> elements you have to devise a scheme either for the input text (if you have control over it) or for preprocessing.

如果您担心双重\ ns或已经存在的元素,您必须为输入文本(如果您可以控制它)或预处理设计方案。

Perhaps replacing all \n\n with \n and all <br />\n with \n before applying nl2br.

在应用nl2br之前,或者用\ n替换所有\ n \ n和\ n以及所有
\ n。

#2


0  

You can try this

你可以试试这个

$text = your source text
$text = preg_replace(
    array('/\n/m',  '/\<br\>\<br\>/m' '/\<br\>$/'),
    array("\n<br>", "<br>", ''),
    $text
);

bye

再见

#1


3  

nl2br does the trick nicely.

nl2br做得很好。

file_get_contents('filename.html');
nl2br($text);

It was designed specifically for your needs.

它专为您的需求而设计。

If you're worried about double \ns or already present <br /> elements you have to devise a scheme either for the input text (if you have control over it) or for preprocessing.

如果您担心双重\ ns或已经存在的元素,您必须为输入文本(如果您可以控制它)或预处理设计方案。

Perhaps replacing all \n\n with \n and all <br />\n with \n before applying nl2br.

在应用nl2br之前,或者用\ n替换所有\ n \ n和\ n以及所有
\ n。

#2


0  

You can try this

你可以试试这个

$text = your source text
$text = preg_replace(
    array('/\n/m',  '/\<br\>\<br\>/m' '/\<br\>$/'),
    array("\n<br>", "<br>", ''),
    $text
);

bye

再见