0

I need to search and replace in a string, I want to replace the last occurrence of a string.

Here's my working code (which just does a normal search/replace):

PREG_REPLACE("/(\b{$abbr}\b)/i", "$long" , $street_address)

Example of expected results:

  • $street_address = "123 St Martin St"
  • $abbr = "St"
  • $long = "Street"
  • return = "123 St Martin Street"

I want only the last occurrence of St replaced with Street.

0

2 Answers 2

2

You can use negative lokahead like this:

$str = "123 St Martin St";
$abbr="(\b)St(\b)";
$long="Street";
var_dump(preg_replace("~$abbr(?!.*?$abbr)~", "$1" . $long . "$2", $str));

OUTPUT:

string(20) "123 St Martin Street"
Sign up to request clarification or add additional context in comments.

1 Comment

This worked well and accommodated various variations of abbreviations. Thanks.
1
PREG_REPLACE("/(.*(\b{$abbr}\b.*)*)\b{$abbr}\b/i", "$1$long" , $street_address )

This might be relatively inefficient.

2 Comments

This only works if the string has st in it and also ends with st.
Rocket is right -- it depends on the value being present elsewhere in the string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.