简体   繁体   English

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

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

Using preg_replace (or other PHP-based option): I need to replace all hyphens in a string, that appear before the last hyphen , with space.使用 preg_replace (或其他基于 PHP 的选项):我需要用空格替换字符串中出现在最后一个 hyphen 之前的所有连字符。

Example #1 of the Result I Need:我需要的结果示例#1:

string = My-Cool-String - 201字符串 = 我的酷字符串 - 201

result = My Cool String - 201结果 = 我的酷字符串 - 201

Example #2 of the Result I Need:我需要的结果示例#2:

Note: Notice that this string example only contains 1 hyphen.注意:请注意,此字符串示例仅包含 1 个连字符。

string = My Cool String - 201字符串 = 我很酷的字符串 - 201

result = My Cool String - 201结果 = 我的酷字符串 - 201

My current code is stripping out ALL hyphens and replacing with space.我当前的代码正在去除所有连字符并用空格替换。

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

Additional Context:附加上下文:

In the example string of My Cool String - 201My Cool String - 201的示例字符串中

My Cool String represents the name of a resort. My Cool String代表度假村的名称。

201 represents the room number. 201代表房间号。

I was running into my originally stated issue when the name of the resort contained hyphens.当度假村的名称包含连字符时,我遇到了我最初提出的问题。

You may use您可以使用

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

See the PHP demo and the regex demo .请参阅PHP 演示正则表达式演示 To account for any whitespace use '/-(?=.*\\s-)/' , or '/-(?=.*\\s-\\s)/' (if there should be whitespaces on both sides of the hyphen).要考虑任何空格,请使用'/-(?=.*\\s-)/''/-(?=.*\\s-\\s)/' (如果连字符的两侧都应该有空格)。

Details细节

  • - - a hyphen - - 一个连字符
  • (?=.* -) - a positive lookahead that requires - after any 0+ chars other than line break chars, as many as possible (use s flag after / to match across line breaks). (?=.* -) - 一个正向前瞻,需要-在除换行符以外的任何 0+ 个字符之后,尽可能多(在/之后使用s标志来匹配换行符)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM