CoastalPro
CoastalPro

Reputation: 83

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.

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

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.

Upvotes: 2

Views: 737

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626870

You may use

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

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).

Upvotes: 2

Related Questions