Skip to content
Advertisement

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.

Example #1 of the Result I Need:

string = My-Cool-String – 201

result = My Cool String – 201

Example #2 of the Result I Need:

Note: Notice that this string example only contains 1 hyphen.

string = My Cool String – 201

result = My Cool String – 201

My current code is stripping out ALL hyphens and replacing with space.

JavaScript

Additional Context:

In the example string of My Cool String - 201

My Cool String represents the name of a resort.

201 represents the room number.

I was running into my originally stated issue when the name of the resort contained hyphens.

Advertisement

Answer

You may use

JavaScript

See the PHP demo and the regex demo. To account for any whitespace use '/-(?=.*s-)/', or '/-(?=.*s-s)/' (if there should be whitespaces on both sides of the hyphen).

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).
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement