正则表达式从字符串右侧替换单个匹配

时间:2022-08-22 12:12:04

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"
  • $ street_address =“123 St Martin St”
  • $abbr = "St"
  • $ abbr =“St”
  • $long = "Street"
  • $ long =“街头”
  • return = "123 St Martin Street"
  • return =“圣马丁街123号”

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

我只希望最后一次出现的St被Street取代。

2 个解决方案

#1


2  

You can use negative lokahead like this:

你可以像这样使用负lokahead:

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

OUTPUT:

OUTPUT:

string(20) "123 St Martin Street"

#2


1  

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

This might be relatively inefficient.

这可能是相对低效的。

#1


2  

You can use negative lokahead like this:

你可以像这样使用负lokahead:

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

OUTPUT:

OUTPUT:

string(20) "123 St Martin Street"

#2


1  

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

This might be relatively inefficient.

这可能是相对低效的。