首页 > 解决方案 > 如何从字符串中删除所有额外/不需要的空格?

问题描述

我正在从 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在循环中使用它来删除双空格和换行符,直到所有额外的空格都被删除?

标签: php

解决方案


推荐阅读