Home > OS >  How to add spaces when a number is followed by a letter in laravel
How to add spaces when a number is followed by a letter in laravel

Time:02-18

I have this text in UTF-8

名古屋市北区,大曽根3丁目 13-2V-

as you can see, in 根3丁 there are no spaces, I would like it to end up being 根 3 丁 for example, the same with -2V and add spaces: - 2 V

As a final result, I am looking for the text to be

名古屋市北区,大曽根 3 丁目 13- 2 V-

that is, adding spaces while there are no numbers next to it (for example that 13-, it must remain the same)

what I currently have removes all the numbers and adds a space to them

$string = preg_replace('/\d /u', ' ', $string);

CodePudding user response:

You can use groups in your regex pattern replacement.

  • Group 1: (\p{L}|\-). Any letter or -
  • Group 2: (\d ). Any number(s)
  • Group 3: (\p{L}|\-). Any letter or -
$string = preg_replace(
    '/(\p{L}|\-)(\d )(\p{L}|\-)/u',  /* pattern */
    '${1} ${2} ${3}',                /* replacement */
    $string                          /* subject */
);

CodePudding user response:

You could assert either a letter or _ to the left and right of the digits, and replace with the full match surrounded by a space on both sides.

(?<=[-\p{L}])\d (?=[\p{L}-])

Regex demo

Example

$s = "名古屋市北区,大曽根3丁目 13-2V-";
$pattern = "/(?<=[-\p{L}])\d (?=[\p{L}-])/u";

echo preg_replace($pattern, " $0 ", $s);

Output

名古屋市北区,大曽根 3 丁目 13- 2 V-
  • Related