php - 如何从字符串中删除所有额外/不需要的空格?
问题描述
我正在从 HTML 页面中提取一些字符串,有时我会得到如下内容:
...
<div>
This is a sample text that extends
over several lines, with linebreaks
in the HTML code and with indentation
spaces to the left.
</div>
...
当我提取其中的文本<div>
并将其存储在一个字符串中时,它将包含大量额外的空格和换行符。我希望将字符串转换为“单行字符串”,即删除不必要的空格和换行符。这是代码的概念部分:
<?php
$my_textpart = extract_textpart_from_div();
$my_string = remove_unwanted_whitespaces($my_textpart);
// --> $my_string = "This is a sample text that extends over several lines, with linebreaks in ... etc ..."
?>
是否有一个简洁或智能的 PHP 函数可以帮助我,或者我会被迫编写一个函数,str_replace
在循环中使用它来删除双空格和换行符,直到所有额外的空格都被删除?
解决方案
推荐阅读
- java - ZipInputStream 转换
- python-3.x - 在任何照明(低或高)下对物体进行图像分割
- maxscript - 如何将数组中的随机旋转值应用于不同的对象
- android - 底部边距导致 RecyclerView 重新排序
- javascript - HTML 列表不会立即更新
- javascript - 如何将 24 小时格式更改为 12 小时?
- angular - Angular:如何在控制台中打印完整的 URL
- c++ - 将 bool 转换为位域中的位
- php - 只有变量应该通过引用传递 - 将 LIMIT 与 bindParam 一起使用时
- php - 在 PHP 数组中查找 ID 并替换它的子项