首页 > 解决方案 > 如何使用 PHP 删除 wordpress 中的重复空格

问题描述

嗨,今天我有一个字符串,它可以带有重复的空格和字符串,目前我正在使用下面的代码来清理

<?php
$string = '    lorem ipsum dolor s            it amet content     ';
trim( $string );

标签: phpwordpress

解决方案


您可以使用下面的代码清除两侧的空格并删除换行符

<?php
    function remove_space( $text ) {
        $text = preg_replace('/[\t\n\r\0\x0B]/', '', $text);
        $text = preg_replace('/([\s])\1+/', ' ', $text);
        $text = trim( $text );
        return $text;
    }

    $exemplo = ' Lorem ipsum dolor sit      amet quaqluer dado
    test content generates              alrel lrea   ';
    $new_string = remove_space( $exemplo );

    echo $new_string; 

推荐阅读