简体   繁体   中英

How would I do the following replacement using PHP preg_replace?

I have a string with one to two white spaces. I want to replace the single white spaces with nothing and the double white spaces with a single white space. If simply try to match on ' 'it will nuke all the white spaces. Is there a way of doing this?

$result = preg_replace('/ (?! )/', '', $subject);

This matches and removes a space only if it's not followed by another space.

Input: 12 34 56 78 90 --> Output: 1234 5678 90

preg_replace('/\s+/',' ',$string);

now all double space will be singled

UPDATE:

$replacements = array(' ','');
 preg_replace('/(\s{2})|(\s{1})/',$replacements,$string);

This way double space become single, and single become nospace;

<?php
    $s = 'SINGLE SPACE-DOUBLE  SPACE';
    echo $s . PHP_EOL;
    $s = strtr(
        $s,
        array(
            '  ' => ' ',
            ' ' => ''
        )
    );
    echo $s . PHP_EOL;
?>

PS: I am testing other cases.

preg_replace isn't necessary.

str_replace('  ', ' ', $string);

or, if you want to make sure there are never to spaces in a row, loop it:

while (strpos($string, '  ') !== false)
    $string = str_replace('  ', ' ', $string);

Unless you mean any whitespace (space, tab, newlines), then you could use:

str_replace(array('  ', "\t\t", "\r\r", "\n\n"), array(' ', "\t", "\r", "\n"), $string);

Single whitespace: " [^ ]" (a whitespace which is not followed by another). Double whitespace: " " .

Match on ' ' (two white spaces). Though for something like this, I think regex is over kill. Just use the str_replace() function and replace all ' ' with ' '.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM