简体   繁体   中英

PHP Regex to find and replace a string of 1 or more pipes with just 1 pipe

I am trying to replace one or more pipes with just one pipe in a string in PHP. The below attempt is not working:

$string = preg_replace('/\|+/', '|', $string);

Here is a sample of input and the desired output:

Input

only | 1494 | | | | | | Limit: None | | Enr: 22 | | | | | | | | |RE

Desired Output

only | 1494 | Limit: None | Enr: 22 | RE

Thanks in advance for solving this headache.

You can use the pattern \\s* to match the spaces.

This code does what you want:

<?php

$text = 'only | 1494 | | | | | | Limit: None | | Enr: 22 | | | | | | | | |RE';

$string = preg_replace('/(\|\s*)+/', '| ', $text);

assert($string === 'only | 1494 | Limit: None | Enr: 22 | RE');

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