W
W
weranda2018-02-07 17:49:50
PHP
weranda, 2018-02-07 17:49:50

How to replace exact matches on word boundary in PHP?

There is a line: Roads are not cleaned not only in the North-Eastern Administrative District, but also in the South-Eastern Administrative District, as well as in the Eastern Administrative District, CJSC ...
There is an array:
Northern Administrative District * North, North-Eastern Administrative District
* North-Eastern
Administrative District * Eastern Southern -Eastern Administrative District
* South-Eastern

Administrative District * Western understand how to go through each first element of the array (separator - *) along the line and replace exact matches with the second element of the array.
I tried preg_replace, but something doesn't work - all matches are replaced, even if it's part of a word, but it should be exactly.
Please tell me how to solve.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
ivankomolin, 2018-02-07
@weranda

$arr = [
  'САО' => 'северный',
  'СВАО' => 'северо-восточный',
  'ВАО'  => 'восточнй',
  'ЮВАО' => 'юго-восточный',
  'ЗАО' => 'западный',
];

$text = str_replace(array_keys($arr), array_values($arr), $text);

If the replacement is by exact occurrence, then you still should not use regular expressions, it is better to use string functions.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question