-1

我正在从 Web 源中获取数据,该源返回的数据通常格式不正确。我想清理文本,它会像这样返回:

Featuring six amazing National Parks: Glacier,
Waterton Lakes, Yellowstone, Grand Teton, Arches, and Canyonlands.

Your tour begins in Chicago where you will board
the Empire Builder
bound for the first National Park on your trip, Glacier, where you will explore the famed Going-to-the-Sun Road and enjoy a full-day excursion to
Waterton Lakes National Park in Canada (passport required).

我想去除单个换行符,但保留双换行符。如何在 PHP 中做到这一点?理想情况下,字符串最终会如下所示:

Featuring six amazing National Parks: Glacier, Waterton Lakes, Yellowstone, Grand Teton, Arches, and Canyonlands.

Your tour begins in Chicago where you will board the Empire Builder bound for the first National Park on your trip, Glacier, where you will explore the famed Going-to-the-Sun Road and enjoy a full-day excursion to Waterton Lakes National Park in Canada (passport required).

我已经尝试过preg_replace( "/\r|\n/", "", $string);,但这会删除双换行符和单个换行符。

4

2 回答 2

1

试试这个正则表达式:

preg_replace('/(?<!\n) *\n(?=[^\n])/', " ", $string);

正则表达式 101 演示

于 2013-10-01T18:25:12.310 回答
0

你可以试试这个:

$result = preg_replace('~(?<!\n)\h*+\r?\n\h*+(?!\r?\n)~', ' ', $text);
于 2013-10-01T18:50:17.223 回答