删除某些字符串之前的空格

时间:2018-11-15 16:42:30

标签: php regex

我可以想到“ foreach字符串替换”的方式,但是觉得regex替换方法会更快,更优雅,但是不幸的是regex不是我最强的东西。

我想要一个这样的字符串

23 AB 5400 DE 68 RG

并将其变成

23AB 5400DE 68RG

数字与后继字母之间的空格数通常为1,但可以变化。

我有一个示例,该示例正在查找组,但是如何去除替换中的空格?

https://regex101.com/r/ODhpQM/2

这是我尝试生成的代码

$re = '/(\d+ +)(AB|DE|RG|DU)/m';
$str = '23 AB 5400 DE 68 RG
        33 DU 88 DE 8723 AB
        55    RG 76  AB  92 DE';
$subst = '\\1\\2';

$result = preg_replace($re, $subst, $str);

echo "The result of the substitution is ".$result;

5 个答案:

答案 0 :(得分:1)

尝试使用正则表达式:@HostListener('document:click', ['$event']) private documentClickHandler(event) { console.log(this.searchbarElem.nativeElement); }

Demo

答案 1 :(得分:1)

您可以使用此环视正则表达式:

$repl = preg_replace('/(?<=\d)\h+(?=\pL)/', '', $str);

RegEx Demo

说明:

  • (?<=\d):在后面断言我们在前面的位置有一个数字
  • \h+:匹配1个以上水平空格
  • (?=\pL):先行断言我们在当前位置之前有一封信

PS:如果您只想在某些已知字符串之前删除空格,请使用此正则表达式:

(?<=\d)\h+(?=(?:AB|DE|RG|DU))

答案 2 :(得分:1)

您可以尝试

$re = '/(\d+)\s+/';
$str = '23 AB 5400 DE 68 RG 33 DU 88 DE 8723 AB 55    RG 76  AB  92 DE';
$subst = '\\1\\2';

$result = preg_replace($re, $subst, $str);
print_r($result);

答案 3 :(得分:1)

另一个选择可能是:

\b\d+\K\h+(?=(?:AB|DE|RG|DU))\b

这将在单词边界\b之间匹配:

  • \d+匹配1个以上的数字
  • \K忘记匹配的内容
  • (?=积极向前看,以断言右边的内容
    • (?:AB|DE|RG|DU)与列出的值之一匹配的替代项
  • )近距离正面预测

Regex demo

并替换为空字符串:

$re = '/\b\d+\K\h+(?=(?:AB|DE|RG|DU))\b/';
$str = '23 AB 5400 DE 68 RG';
$result = preg_replace($re, '', $str);
echo $result; // 23AB 5400DE 68RG

答案 4 :(得分:1)

除非我丢失了某些内容,否则不理会这些数字,而只需将所有非数字替换为空格之前的空格,并以相同的文本加上空格即可。

$result = preg_replace('/\s+(\D+)/', '$1', $string);

即匹配" AB"之类的东西,并将其替换为"AB"