仅在字符正则表达式之前匹配空格并用短划线替换空格

时间:2022-08-09 20:13:58

What I'm after is to replace a space with a dash - BUT only if that space is has a character after it. Reason being is I have an array of strings some of which have spaces inserted after the final word or character. (this is out of my control). e.g In the example below I have used %20 to show where a space is string1 = farmer%20jones string2 = farmer%20jim%20

我所追求的是用短划线替换空格 - 但前提是该空格后面有一个字符。原因是我有一个字符串数组,其中一些字符串在最后的单词或字符后面插入了空格。 (这是我无法控制的)。例如,在下面的示例中,我使用%20来显示空格是string1 =农民%20jones string2 =农民%20jim%20

I have the following regex preg_replace('/\s./', '-', $string);

我有以下正则表达式preg_replace('/ \ s。/',' - ',$ string);

I think I'm half way there, but the above searches for a space preceding a character and replaces that with a -

我想我已经走了一半,但上面搜索了一个字符前面的空格并用 - 替换了 -

What I get with the above regex is string1 = farmer-jones string2 = farmer-jim-

我用上面的正则表达式得到的是string1 = farmer-jones string2 = farmer-jim-

What I want is: string1 = farmer-jones string2 = farmer-jim

我想要的是:string1 = farmer-jones string2 = farmer-jim

I don't want that trailing - to be added.

我不希望添加尾随。

Any help much appreciated

任何帮助非常感谢

1 个解决方案

#1


2  

You can use negative lookahead here:

您可以在此处使用否定前瞻:

$repl = preg_replace('/\h+(?!$)/', '-', $string);
  • \h+ will match 1 or more horizontal whitespace.
  • \ h +将匹配1个或更多水平空格。

  • (?!$) will assert that next position is not end of line.
  • (?!$)将声明下一个位置不是行尾。

RegEx Demo

#1


2  

You can use negative lookahead here:

您可以在此处使用否定前瞻:

$repl = preg_replace('/\h+(?!$)/', '-', $string);
  • \h+ will match 1 or more horizontal whitespace.
  • \ h +将匹配1个或更多水平空格。

  • (?!$) will assert that next position is not end of line.
  • (?!$)将声明下一个位置不是行尾。

RegEx Demo