查找并替换两个可变长度整数之间的连字符(-)


Finding and replacing a hyphen (-) between two integers of variable length

我有一大块文本,在该文本中有几个类似201014120 - 10的文本出现。还有带有普通连字符(-)的文本。

我要做的是用逗号,替换两个数字之间的连字符,但不是替换文本中的任何其他连字符。我想这样做与PHP的preg_replace

数字是不相同的,每个数字的长度将不相同的所有文本。

我已经尝试了不同类型的正则表达式,无论是与代码和这个非常好的网站。

您可以使用lookaround来确保您只匹配被数字包围的连字符:

preg_replace('/(?<='d)'s*-'s*(?='d)/', ', ', $input);

(?<='d)是正向后看:它只允许regex匹配,如果它前面有一个数字。相反,(?='d)是正向的。正则表达式将匹配(并因此替换)连字符周围的任何空白。

尝试:

$str='e-mail 201014120 - 10 e - mail 201014120-10';    
echo preg_replace('/('d+'s*)-('s*'d+)/','${1},${2}',$str);
>>> e-mail 201014120 , 10 e - mail 201014120,10

Match ('d+'s*)-('d+'s*):

'd+ # One or more digits 
's* # Zero or more white space characters
-   # Literal hypen
()  # Capture group 

替换${1},${2}

${1} # The first captured group
,    # A literal comma
${2} # The second captured group

未测试:

preg_replace("/('d+)-('d+)/g","$1,$2",$text);

或者,如果你的文本是"数字" "空白" "连字符" "空白" "数字"

preg_replace("/('d+'w*)-('w*'d+)/g","$1,$2",$text);
<?php
$string = '201014120 - 10';
$pattern = '/('d+) - ('d+)/';
$replacement = '$1,$2';
echo preg_replace($pattern, $replacement, $string);
?>