0

Let's say I have a string.

`$str = "   Hi, my  name is 
         Petr"; `

Expecting: $str = " Hi, my name is Petr";

I need to replace all the white spaces '....' at the beginning of the string and then if there is a multiple number of white space between words in the string then replace it with one empty space.

I want to do this with the regex function 'preg_replace'.

But I don't know how to "/^\s+/" for remove white spaces on the start of string and "/\s+/" for white spaces between words in a string. Is it possible to merge the two formula patterns into one pattern? If so, what would the formula look like?

Petr Fořt Fru-Fru
  • 858
  • 2
  • 8
  • 23

2 Answers2

1

I guess,

$str = '   Hi, my  name is
         Petr';
$result = preg_replace('/\s{2,}/', ' ', $str);
$result = preg_replace('/^\s*|\s*$/', '', $result);

echo $result;

might work OK, which'd output:

Hi, my name is Petr
Emma
  • 27,428
  • 11
  • 44
  • 69
1

There are a couple of ways to achieve this. You can take advantage of the fact that preg_replace can take an array of patterns and replacements to use your two regexes:

$str = "   Hi, my  name is 
         Petr";
echo preg_replace(array('/^\s+/', '/\s+/'), array('', ' '), $str) . "\n";

Alternatively, you can use a slightly more complicated regex using a positive lookbehind to remove any sequence of whitespace that is preceded by either the start of string (^) or other whitespace:

echo preg_replace('/(?<=^|\s)\s+/', '', $str);

In both cases the output is

Hi, my name is Petr
Hi, my name is Petr

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95
  • Thank you for help. I will try both your methods. @Nick – Petr Fořt Fru-Fru Dec 09 '19 at 02:15
  • @PetrFořtFru-Fru no worries - but you shouldn't accept an answer until after you've had a chance to test it. – Nick Dec 09 '19 at 02:43
  • Do not worry. I've already tried both regexes. I used the easier method. So far I'm trying to understand regexes, I'm learning. Thanks again. @Nick – Petr Fořt Fru-Fru Dec 09 '19 at 02:59
  • Please, I still have a question about regex. Can this regex be applied in MariaDB SQL? MariaDB has a function REGEXP_REPLACE but probably I'm not good enough to write a functional regex for MariaDB. Thank you. @Nick – Petr Fořt Fru-Fru Dec 11 '19 at 09:55
  • 1
    @PetrFořtFru-Fru yes, you just need to use a nested `regexp_replace`, and escape the backslashes: https://dbfiddle.uk/?rdbms=mariadb_10.2&fiddle=143b6668305f42b0dc16266f84ee8372 – Nick Dec 11 '19 at 11:46