Home > Software engineering >  Only one space between two character with regex
Only one space between two character with regex

Time:05-18

I have an input field which accept 2 character data like

"ক খ "," কখ"," কখ ", "ক   খ" 

I want to format them into

"ক খ"

only one space between them, i need the regex of it for a php function.

CodePudding user response:

You can do this quite easily with normal PHP code. For instance:

<?php

$input = ["ক খ "," কখ"," কখ ", "ক   খ"];
$output = [];

foreach ($input as $str) {
    $output[] = trim(str_replace(['    ', '   ', '  '], ' ', $str));
}

var_export($output);

This will replace up to four spaces by one space and trim the result to remove any spaces at the begin or end. The output is:

array (
  0 => 'ক খ',
  1 => 'কখ',
  2 => 'কখ',
  3 => 'ক খ',
)

See: PHP Fiddle

The advantage of the code is that it is easy to understand. You could have written it yourself, unlike the regular expression. And because it is easy to understand it won't do unexpected things and will be easy to change it later on.

CodePudding user response:

Try this:

/\s*([\p{Bengali}])(?:\s*)?([\p{Bengali}])\s*/u

https://www.phpliveregex.com/p/EKD

<?php
  $str = "ক   খ" ;
  echo preg_replace('/\s*([\p{Bengali}])(?:\s*)?([\p{Bengali}])\s*/u', '$1 $2', $str);
?>

Output:

ক খ

CodePudding user response:

it was my solution

$serial = $row[0];
// remove all space
$serial = preg_replace('/\s /', '', $serial);
// add one space
$to = [
"ক ক", "ক খ", "ক গ", "ক ঘ", "ক ঙ", "ক চ", "ক ছ", "ক জ", "ক ঝ", "ক ঞ", "ক ট", "ক ঠ", "ক ড", "ক ঢ",
"ক থ", "ক দ", "ক ন", "ক প", "ক ফ", "ক ব", "ক ম", "ক ল", "ক শ", "ক ষ", "ক স", "ক হ", "খ ক", "খ খ", "খ গ",
 "খ ঘ", "খ ঙ", "খ চ", "খ ছ", "খ জ", "খ ঝ", "খ ঞ", "খ ট", "খ ঠ", "খ ড", "খ ঢ", "খ থ", "খ দ", "খ ন", "খ প",
 "খ ফ", "খ ব", "খ ম", "খ ল", "খ শ", "খ ষ", "খ স", "গ খ", "খ হ", "গ ক", "গ গ", "গ ঘ", "গ ঙ", "গ চ", "গ ছ",
 "গ জ", "গ ঝ", "গ ঞ", "গ ট", "গ ঠ", "গ ড", "গ ঢ", "গ থ", "গ দ"
];
$from = [
"কক", "কখ", "কগ", "কঘ", "কঙ", "কচ", "কছ", "কজ", "কঝ", "কঞ", "কট", "কঠ", "কড", "কঢ",
"কথ", "কদ", "কন", "কপ", "কফ", "কব", "কম", "কল", "কশ", "কষ", "কস", "কহ", "খক", "খ খ", "খ গ",
"খঘ", "খঙ", "খচ", "খছ", "খজ", "খঝ", "খঞ", "খট", "খঠ", "খড", "খঢ", "খথ", "খদ", "খন", "খপ",
"খফ", "খব", "খম", "খল", "খশ", "খষ", "খস", "গখ", "খহ", "গক", "গগ", "গঘ", "গঙ", "গচ", "গছ",
"গ জ", "গঝ", "গঞ", "গট", "গঠ", "গড", "গঢ", "গথ", "গদ"
];
$serial = Str::replace($from, $to, $serial);

Now using it, it also work fine.

echo preg_replace('/\s*([\p{Bengali}])(?:\s*)?([\p{Bengali}])\s*/u', '$1 $2', $serial);
  • Related