PHP preg_replace:用 Space 替换字符串中出现在最后一个连字符之前的所有连字符

PHP preg_replace: Replace All Hyphens in String That Appear Before the Last Hyphen w/ Space

使用 preg_replace(或其他基于 PHP 的选项):我需要替换字符串中的所有连字符,出现在最后一个连字符 之前, space.

我需要的结果示例 #1:

string = My-Cool-String - 201

结果 = 我的酷弦 - 201

我需要的结果示例 #2:

注意:请注意,此字符串示例仅包含 1 个连字符。

string = 我的酷弦 - 201

结果 = 我的酷弦 - 201

我当前的代码删除所有连字符并替换为 space。

$origString = 'My-Cool-String - 201';
$newString = preg_replace("/[^A-Za-z0-9]/", ' ', $origString);

其他上下文:

My Cool String - 201

的示例字符串中

My Cool String代表一个度假村的名字。

201代表房间号

当度假村的名称包含连字符时,我 运行 陷入了我最初提出的问题。

您可以使用

preg_replace('/-(?=.* -)/', ' ', $origString)

PHP demo and the regex demo。要考虑任何空格,请使用 '/-(?=.*\s-)/''/-(?=.*\s-\s)/'(如果连字符两边都应该有空格)。

详情

  • - - 一个连字符
  • (?=.* -) - 在除换行字符以外的任何 0+ 个字符之后需要 - 的积极前瞻,尽可能多(在 / 之后使用 s 标志匹配换行符)。